@google-cloud/datastore

  • Version 6.5.0
  • Published
  • 2.92 MB
  • 8 dependencies
  • Apache-2.0 license

Install

npm i @google-cloud/datastore
yarn add @google-cloud/datastore
pnpm add @google-cloud/datastore

Overview

Cloud Datastore Client Library for Node.js

Index

Variables

Classes

Interfaces

Type Aliases

Variables

variable v1

const v1: any;

    Classes

    class Datastore

    class Datastore extends DatastoreRequest {}
    • Idiomatic class for interacting with Cloud Datastore. Uses the lower-level v1.DatastoreClient class under the hood.

      In addition to the constructor options shown here, the Datastore class constructor accepts the same options accepted by v1.DatastoreClient.

      The Datastore Emulator

      Make sure you have the gcloud SDK installed, then run:

      $ gcloud beta emulators datastore start --no-legacy

      You will see the following printed:

      [datastore] API endpoint: http://localhost:8005 [datastore] If you are using a library that supports the DATASTORE_EMULATOR_HOST environment variable, run: [datastore] [datastore] export DATASTORE_EMULATOR_HOST=localhost:8005 [datastore] [datastore] Dev App Server is now running.

      Set that environment variable and your localhost Datastore will automatically be used. You can also pass this address in manually with apiEndpoint.

      Additionally, DATASTORE_PROJECT_ID is recognized. If you have this set, you don't need to provide a projectId.

      {DatastoreRequest}

      Parameter options

      Configuration options.

      Parameter

      {string} [options.apiEndpoint] Override the default API endpoint used to reach Datastore. This is useful for connecting to your local Datastore server (usually "http://localhost:8080").

      Parameter

      {string} [options.namespace] Namespace to isolate transactions to.

      Example 1

      Import the client library const {Datastore} = require('@google-cloud/datastore');

      Example 2

      Create a client that uses Application Default Credentials (ADC): const datastore = new Datastore();

      Example 3

      Create a client with explicit credentials: const datastore = new Datastore({ projectId: 'your-project-id', keyFilename: '/path/to/keyfile.json' });

      Example 4

      Retrieving Records const {Datastore} = require('@google-cloud/datastore'); const datastore = new Datastore();

      // Records, called "entities" in Datastore, are retrieved by using a key. The // key is more than a numeric identifier, it is a complex data structure that // can be used to model relationships. The simplest key has a string kind // value, and either a numeric id value, or a string name value. // // A single record can be retrieved with Datastore#key and // Datastore#get. //- const key = datastore.key(['Company', 'Google']);

      datastore.get(key, function(err, entity) { // entity = The record. // entity[datastore.KEY] = The key for this entity. });

      //- // Querying Records // // Create a query with Datastore#createQuery. //- const query = datastore.createQuery('Company');

      //- // Multiple records can be found that match criteria with // Query#filter. //- query.filter('location', 'CA');

      //- // Records can also be ordered with Query#order. //- query.order('name');

      //- // The number of records returned can be specified with // Query#limit. //- query.limit(5);

      //- // Records' key structures can also be queried with // Query#hasAncestor. //- const ancestorKey = datastore.key(['ParentCompany', 'Alphabet']);

      query.hasAncestor(ancestorKey);

      //- // Run the query with Datastore#runQuery. //- datastore.runQuery(query, (err, entities) => { // entities = An array of records.

      // Access the Key object for an entity. const firstEntityKey = entities[0][datastore.KEY]; });

      Example 5

      Paginating Records // Imagine building a website that allows a user to sift through hundreds of // their contacts. You'll likely want to only display a subset of these at // once, so you set a limit. //- const express = require('express'); const app = express();

      const NUM_RESULTS_PER_PAGE = 15;

      app.get('/contacts', (req, res) => { const query = datastore.createQuery('Contacts') .limit(NUM_RESULTS_PER_PAGE);

      if (req.query.nextPageCursor) { query.start(req.query.nextPageCursor); }

      datastore.runQuery(query, (err, entities, info) => { if (err) { // Error handling omitted. return; }

      // Respond to the front end with the contacts and the cursoring token // from the query we just ran. const frontEndResponse = { contacts: entities };

      // Check if more results may exist. if (info.moreResults !== datastore.NO_MORE_RESULTS) { frontEndResponse.nextPageCursor = info.endCursor; }

      res.render('contacts', frontEndResponse); }); });

      Example 6

      Creating Records // New entities can be created and persisted with Datastore#save. // The entitiy must have a key to be saved. If you don't specify an // identifier for the key, one is generated for you. // // We will create a key with a name identifier, "Google". //- const key = datastore.key(['Company', 'Google']);

      const data = { name: 'Google', location: 'CA' };

      datastore.save({ key: key, data: data }, (err) => { if (!err) { // Record saved successfully. } });

      //- // We can verify the data was saved by using Datastore#get. //- datastore.get(key, (err, entity) => { // entity = { // name: 'Google', // location: 'CA' // } });

      //- // If we want to update this record, we can modify the data object and re- // save it. //- data.symbol = 'GOOG';

      datastore.save({ key: key, // defined above (datastore.key(['Company', 'Google'])) data: data }, (err, entity) => { if (!err) { // Record updated successfully. } });

      Example 7

      Deleting Records // Entities can be removed from Datastore by passing the entity's key object // to Datastore#delete. //- const key = datastore.key(['Company', 'Google']);

      datastore.delete(key, (err) => { if (!err) { // Record deleted successfully. } });

      Example 8

      Transactions // Complex logic can be wrapped in a transaction with // Datastore#transaction. All queries and updates run within // the transaction will be applied when the done function is called. //- const transaction = datastore.transaction();

      transaction.run((err) => { if (err) { // Error handling omitted. }

      const key = datastore.key(['Company', 'Google']);

      transaction.get(key, (err, entity) => { if (err) { // Error handling omitted. }

      entity.symbol = 'GOOG';

      transaction.save(entity);

      transaction.commit((err) => { if (!err) { // Transaction committed successfully. } }); }); });

      Example 9

      Queries with Ancestors const {Datastore} = require('@google-cloud/datastore'); const datastore = new Datastore();

      const customerId1 = 2993844; const customerId2 = 4993882; const customerKey1 = datastore.key(['Customer', customerId1]); const customerKey2 = datastore.key(['Customer', customerId2]); const cookieKey1 = datastore.key(['Customer', customerId1, 'Cookie', 'cookie28839']); // child entity const cookieKey2 = datastore.key(['Customer', customerId1, 'Cookie', 'cookie78984']); // child entity const cookieKey3 = datastore.key(['Customer', customerId2, 'Cookie', 'cookie93911']); // child entity

      const entities = [];

      entities.push({ key: customerKey1, data: { name: 'Jane Doe', address: '4848 Liller' } });

      entities.push({ key: customerKey2, data: { name: 'John Smith', address: '4848 Pine' } });

      entities.push({ key: cookieKey1, data: { cookieVal: 'dj83kks88rkld' } });

      entities.push({ key: cookieKey2, data: { cookieVal: 'sj843ka99s' } });

      entities.push({ key: cookieKey3, data: { cookieVal: 'otk82k2kw' } });

      datastore.upsert(entities);

      const query = datastore.createQuery().hasAncestor(customerKey1);

      datastore.runQuery(query, (err, entities) => { for (let entity of entities) { console.log(entity[datastore.KEY]); } });

      const query2 = datastore.createQuery().hasAncestor(customerKey2);

      datastore.runQuery(query2, (err, entities) => { for (let entity of entities) { console.log(entity[datastore.KEY]); } });

      datastore.runQuery(query2, (entities) => { console.log(entities); });

      See Also

    constructor

    constructor(options?: DatastoreOptions);

      property auth

      auth: any;

        property baseUrl_

        baseUrl_?: string;

          property clients_

          clients_: Map<string, any>;

            property customEndpoint_

            customEndpoint_?: boolean;

              property DatastoreRequest

              DatastoreRequest: typeof DatastoreRequest;
              • DatastoreRequest class.

                Datastore.DatastoreRequest

                See Also

                • DatastoreRequest {constructor}

              property defaultBaseUrl_

              defaultBaseUrl_: string;

                property KEY

                static KEY: Symbol;
                • Access the Key from an Entity object.

                  Datastore#KEY {symbol}

                property KEY

                KEY: Symbol;

                  property MORE_RESULTS_AFTER_CURSOR

                  static MORE_RESULTS_AFTER_CURSOR: string;

                  property MORE_RESULTS_AFTER_CURSOR

                  MORE_RESULTS_AFTER_CURSOR: string;

                    property MORE_RESULTS_AFTER_LIMIT

                    static MORE_RESULTS_AFTER_LIMIT: string;

                    property MORE_RESULTS_AFTER_LIMIT

                    MORE_RESULTS_AFTER_LIMIT: string;

                      property namespace

                      namespace?: string;

                        property NO_MORE_RESULTS

                        static NO_MORE_RESULTS: string;

                        property NO_MORE_RESULTS

                        NO_MORE_RESULTS: string;

                          property options

                          options: DatastoreOptions;

                            property port_

                            port_?: number;

                              property Query

                              Query: typeof Query;
                              • Query class.

                                Datastore.Query

                                See Also

                                • Query {constructor}

                              property Transaction

                              Transaction: typeof Transaction;
                              • Transaction class.

                                Datastore.Transaction

                                See Also

                                • Transaction {constructor}

                              method createQuery

                              createQuery: {
                              (kind?: string): Query;
                              (kind?: string[]): Query;
                              (namespace: string, kind: string): Query;
                              (namespace: string, kind: string[]): Query;
                              };

                                method determineBaseUrl_

                                determineBaseUrl_: (customApiEndpoint?: string) => void;
                                • Determine the appropriate endpoint to use for API requests. If not explicitly defined, check for the "DATASTORE_EMULATOR_HOST" environment variable, used to connect to a local Datastore server.

                                  Parameter customApiEndpoint

                                  Custom API endpoint.

                                method double

                                static double: (value: number) => entity.Double;
                                • Helper function to get a Datastore Double object.

                                  Parameter value

                                  The double value.

                                  Returns

                                  {object}

                                  Example 1

                                  const {Datastore} = require('@google-cloud/datastore'); const datastore = new Datastore(); const threeDouble = datastore.double(3.0);

                                method export

                                export: {
                                (config: ExportEntitiesConfig): Promise<LongRunningResponse>;
                                (config: ExportEntitiesConfig, callback: LongRunningCallback): void;
                                };

                                  method geoPoint

                                  static geoPoint: (coordinates: entity.Coordinates) => entity.GeoPoint;
                                  • Helper function to get a Datastore Geo Point object.

                                    Parameter coordinates

                                    Coordinate value.

                                    Parameter

                                    {number} coordinates.latitude Latitudinal value.

                                    Parameter

                                    {number} coordinates.longitude Longitudinal value.

                                    Returns

                                    {object}

                                    Example 1

                                    const {Datastore} = require('@google-cloud/datastore'); const datastore = new Datastore(); const coordinates = { latitude: 40.6894, longitude: -74.0447 };

                                    const geoPoint = datastore.geoPoint(coordinates);

                                    //- // List all companies that are located at 40.123 latitude // and -74.0447 longitude. //- const query = datastore.createQuery('Company'); const companyQuery = query .filter('geoPoint.latitude', datastore.double(40.123)) .filter('geoPoint.longitude', datastore.double(-74.0447));

                                  method getIndexes

                                  getIndexes: {
                                  (options?: GetIndexesOptions): Promise<GetIndexesResponse>;
                                  (options: GetIndexesOptions, callback: GetIndexesCallback): void;
                                  (callback: GetIndexesCallback): void;
                                  };

                                    method getIndexesStream

                                    getIndexesStream: (options?: GetIndexesOptions) => any;
                                    • Get all of the indexes in this project as a readable object stream.

                                      Parameter options

                                      Configuration object. See Datastore#getIndexes for a complete list of options.

                                      Returns

                                      {ReadableStream}

                                    method getProjectId

                                    getProjectId: () => Promise<string>;

                                      method import

                                      import: {
                                      (config: ImportEntitiesConfig): Promise<LongRunningResponse>;
                                      (config: ImportEntitiesConfig, callback: LongRunningCallback): void;
                                      };

                                        method index

                                        index: (id: string) => Index;
                                        • Get a reference to an Index.

                                          Parameter id

                                          The index name or id.

                                          Returns

                                          {Index}

                                        method insert

                                        insert: {
                                        (entities: Entities): Promise<InsertResponse>;
                                        (entities: any, callback: CommitCallback): void;
                                        };

                                          method int

                                          static int: (value: number | string) => entity.Int;
                                          • Helper function to get a Datastore Integer object.

                                            This is also useful when using an ID outside the bounds of a JavaScript Number object.

                                            Parameter value

                                            The integer value.

                                            Returns

                                            {object}

                                            Example 1

                                            const {Datastore} = require('@google-cloud/datastore'); const datastore = new Datastore(); const sevenInteger = datastore.int(7);

                                            //- // Create an Int to support long Key IDs. //- const key = datastore.key([ 'Kind', datastore.int('100000000000001234') ]);

                                          method isDouble

                                          static isDouble: (value?: {}) => boolean;
                                          • Helper function to check if something is a Datastore Double object.

                                            Parameter value

                                            Returns

                                            {boolean}

                                            Example 1

                                            const {Datastore} = require('@google-cloud/datastore'); const datastore = new Datastore(); datastore.isDouble(0.42); // false datastore.isDouble(datastore.double(0.42)); // true

                                          method isGeoPoint

                                          static isGeoPoint: (value?: {}) => boolean;
                                          • Helper function to check if something is a Datastore Geo Point object.

                                            Parameter value

                                            Returns

                                            {boolean}

                                            Example 1

                                            const {Datastore} = require('@google-cloud/datastore'); const datastore = new Datastore(); const coordinates = { latitude: 0, longitude: 0 };

                                            datastore.isGeoPoint(coordinates); // false datastore.isGeoPoint(datastore.geoPoint(coordinates)); // true

                                          method isInt

                                          static isInt: (value?: {}) => boolean;
                                          • Helper function to check if something is a Datastore Integer object.

                                            Parameter value

                                            Returns

                                            {boolean}

                                            Example 1

                                            const {Datastore} = require('@google-cloud/datastore'); const datastore = new Datastore(); datastore.isInt(42); // false datastore.isInt(datastore.int(42)); // true

                                          method isKey

                                          static isKey: (value?: {}) => boolean;
                                          • Helper function to check if something is a Datastore Key object.

                                            Parameter value

                                            Returns

                                            {boolean}

                                            Example 1

                                            const {Datastore} = require('@google-cloud/datastore'); const datastore = new Datastore(); datastore.isKey({path: ['Company', 123]}); // false datastore.isKey(datastore.key(['Company', 123])); // true

                                          method key

                                          key: {
                                          (options: entity.KeyOptions): entity.Key;
                                          (path: PathType[]): entity.Key;
                                          (path: string): entity.Key;
                                          };

                                            method keyFromLegacyUrlsafe

                                            keyFromLegacyUrlsafe: (key: string) => entity.Key;
                                            • Helper to convert URL safe key string to entity key object

                                              This is intended to work with the "legacy" representation of a datastore "Key" used within Google App Engine (a so-called "Reference").

                                              Parameter key

                                              Entity key object.

                                              Parameter locationPrefix

                                              Optional . The location prefix of an App Engine project ID. Often this value is 's~', but may also be 'e~', or other location prefixes currently unknown.

                                              Returns

                                              {string} Created urlsafe key.

                                              Example 1

                                              const {Datastore} = require('@google-cloud/datastore'); const datastore = new Datastore(); const urlSafeKey = 'ag9ncmFzcy1jbHVtcC00NzlyEwsSB0NvbXBhbnkiBkdvb2dsZQw';

                                              datastore.keyFromLegacyUrlsafe(key);

                                            method keyToLegacyUrlSafe

                                            keyToLegacyUrlSafe: {
                                            (key: entity.Key, locationPrefix?: string): Promise<string>;
                                            (key: entity.Key, callback: KeyToLegacyUrlSafeCallback): void;
                                            (
                                            key: entity.Key,
                                            locationPrefix: string,
                                            callback: KeyToLegacyUrlSafeCallback
                                            ): void;
                                            };

                                              method save

                                              save: {
                                              (entities: Entities, gaxOptions?: any): Promise<SaveResponse>;
                                              (entities: any, gaxOptions: any, callback: CommitCallback): void;
                                              (entities: any, callback: CommitCallback): void;
                                              };

                                                method transaction

                                                transaction: (options?: TransactionOptions) => Transaction;
                                                • Create a new Transaction object.

                                                  Parameter options

                                                  Configuration object.

                                                  Parameter

                                                  {string} [options.id] The ID of a previously run transaction.

                                                  Parameter

                                                  {boolean} [options.readOnly=false] A read-only transaction cannot modify entities.

                                                  Returns

                                                  {Transaction}

                                                  Example 1

                                                  const {Datastore} = require('@google-cloud/datastore'); const datastore = new Datastore(); const transaction = datastore.transaction();

                                                method update

                                                update: {
                                                (entities: Entities): Promise<UpdateResponse>;
                                                (entities: any, callback: CommitCallback): void;
                                                };

                                                  method upsert

                                                  upsert: {
                                                  (entities: Entities): Promise<UpsertResponse>;
                                                  (entities: any, callback: CommitCallback): void;
                                                  };

                                                    class DatastoreRequest

                                                    class DatastoreRequest {}
                                                    • Handle logic for Datastore API operations. Handles request logic for Datastore.

                                                      Creates requests to the Datastore endpoint. Designed to be inherited by the Datastore and Transaction classes.

                                                    property datastore

                                                    datastore: Datastore;

                                                      property id

                                                      id: string;

                                                        property requestCallbacks_

                                                        requestCallbacks_: any;

                                                          property requests_

                                                          requests_: any;

                                                            method allocateIds

                                                            allocateIds: {
                                                            (
                                                            key: entity.Key,
                                                            options: AllocateIdsOptions | number
                                                            ): Promise<AllocateIdsResponse>;
                                                            (
                                                            key: entity.Key,
                                                            options: number | AllocateIdsOptions,
                                                            callback: AllocateIdsCallback
                                                            ): void;
                                                            };

                                                              method createReadStream

                                                              createReadStream: (keys: Entities, options?: CreateReadStreamOptions) => any;
                                                              • Retrieve the entities as a readable object stream.

                                                                Parameter keys

                                                                Datastore key object(s).

                                                                Parameter options

                                                                Optional configuration. See Datastore#get for a complete list of options.

                                                                Throws

                                                                {Error} If at least one Key object is not provided.

                                                                Example 1

                                                                const keys = [ datastore.key(['Company', 123]), datastore.key(['Product', 'Computer']) ];

                                                                datastore.createReadStream(keys) .on('error', (err) => {}) .on('data', (entity) => { // entity is an entity object. }) .on('end', () => { // All entities retrieved. });

                                                              method delete

                                                              delete: {
                                                              (keys: Entities, gaxOptions?: any): Promise<DeleteResponse>;
                                                              (keys: any, callback: CommitCallback): void;
                                                              (keys: any, gaxOptions: any, callback: CommitCallback): void;
                                                              };

                                                                method get

                                                                get: {
                                                                (
                                                                keys: entity.Key | entity.Key[],
                                                                options?: CreateReadStreamOptions
                                                                ): Promise<GetResponse>;
                                                                (keys: entity.Key | entity.Key[], callback: GetCallback): void;
                                                                (
                                                                keys: entity.Key | entity.Key[],
                                                                options: RunQueryOptions,
                                                                callback: GetCallback
                                                                ): void;
                                                                };

                                                                  method merge

                                                                  merge: {
                                                                  (entities: Entities): Promise<CommitResponse>;
                                                                  (entities: any, callback: CommitCallback): void;
                                                                  };

                                                                    method prepareEntityObject_

                                                                    static prepareEntityObject_: (obj: Entity) => PrepareEntityObjectResponse;
                                                                    • Format a user's input to mutation methods. This will create a deep clone of the input, as well as allow users to pass an object in the format of an entity.

                                                                      Both of the following formats can be supplied supported:

                                                                      datastore.save({ key: datastore.key('Kind'), data: { foo: 'bar' } }, (err) => {})

                                                                      const entity = { foo: 'bar' } entity[datastore.KEY] = datastore.key('Kind') datastore.save(entity, (err) => {})

                                                                      Parameter obj

                                                                      The user's input object.

                                                                      See Also

                                                                    method prepareGaxRequest_

                                                                    prepareGaxRequest_: (config: RequestConfig, callback: Function) => void;

                                                                    method request_

                                                                    request_: (config: RequestConfig, callback: RequestCallback) => void;

                                                                      method requestStream_

                                                                      requestStream_: (config: RequestConfig) => AbortableDuplex;
                                                                      • Make a request as a stream.

                                                                        Parameter config

                                                                        Configuration object.

                                                                        Parameter

                                                                        {object} config.gaxOpts GAX options.

                                                                        Parameter

                                                                        {string} config.client The name of the gax client.

                                                                        Parameter

                                                                        {string} config.method The gax method to call.

                                                                        Parameter

                                                                        {object} config.reqOpts Request options.

                                                                      method runQuery

                                                                      runQuery: {
                                                                      (query: Query, options?: RunQueryOptions): Promise<RunQueryResponse>;
                                                                      (query: Query, options: RunQueryOptions, callback: RunQueryCallback): void;
                                                                      (query: Query, callback: RunQueryCallback): void;
                                                                      };

                                                                        method runQueryStream

                                                                        runQueryStream: (query: Query, options?: RunQueryStreamOptions) => any;
                                                                        • Get a list of entities as a readable object stream.

                                                                          See Datastore#runQuery for a list of all available options.

                                                                          Parameter query

                                                                          Query object.

                                                                          Parameter options

                                                                          Optional configuration.

                                                                          Parameter

                                                                          {object} [options.gaxOptions] Request configuration options, outlined here: https://googleapis.github.io/gax-nodejs/global.html#CallOptions.

                                                                          Example 1

                                                                          datastore.runQueryStream(query) .on('error', console.error) .on('data', (entity) => { // Access the Key object for this entity. const key = entity[datastore.KEY]; }) .on('info', (info) => {}) .on('end', () => { // All entities retrieved. });

                                                                          //- // If you anticipate many results, you can end a stream early to prevent // unnecessary processing and API requests. //- datastore.runQueryStream(query) .on('data', (entity) => { this.end(); });

                                                                        class Index

                                                                        class Index {}
                                                                        • Parameter datastore

                                                                          The parent instance of this index.

                                                                          Parameter id

                                                                          The index name or id.

                                                                          Example 1

                                                                          const {Datastore} = require('@google-cloud/datastore'); const datastore = new Datastore(); const index = datastore.index('my-index');

                                                                        constructor

                                                                        constructor(datastore: Datastore, id: string);

                                                                          property datastore

                                                                          datastore: Datastore;

                                                                            property id

                                                                            id: string;

                                                                              property metadata

                                                                              metadata?: google.datastore.admin.v1.IIndex;

                                                                                method get

                                                                                get: {
                                                                                (gaxOptions?: any): Promise<GetIndexResponse>;
                                                                                (callback: GetIndexCallback): void;
                                                                                (gaxOptions: any, callback: GetIndexCallback): void;
                                                                                };

                                                                                  method getMetadata

                                                                                  getMetadata: {
                                                                                  (gaxOptions?: any): Promise<IndexGetMetadataResponse>;
                                                                                  (callback: IndexGetMetadataCallback): void;
                                                                                  (gaxOptions: any, callback: IndexGetMetadataCallback): void;
                                                                                  };

                                                                                    class Query

                                                                                    class Query {}
                                                                                    • Build a Query object.

                                                                                      **Queries are built with {module:datastore#createQuery} and Transaction#createQuery.**

                                                                                      Parameter scope

                                                                                      The parent scope the query was created from.

                                                                                      Parameter namespace

                                                                                      Namespace to query entities from.

                                                                                      Parameter kinds

                                                                                      Kind to query.

                                                                                      Example 1

                                                                                      const {Datastore} = require('@google-cloud/datastore'); const datastore = new Datastore(); const query = datastore.createQuery('AnimalNamespace', 'Lion');

                                                                                      See Also

                                                                                    constructor

                                                                                    constructor(scope?: Transaction | Datastore, kinds?: string[]);

                                                                                      constructor

                                                                                      constructor(
                                                                                      scope?: Transaction | Datastore,
                                                                                      namespace?: string,
                                                                                      kinds?: string[]
                                                                                      );

                                                                                        property endVal

                                                                                        endVal: any;

                                                                                          property filters

                                                                                          filters: Filter[];

                                                                                            property groupByVal

                                                                                            groupByVal: {}[];

                                                                                              property kinds

                                                                                              kinds: string[];

                                                                                                property limitVal

                                                                                                limitVal: number;

                                                                                                  property namespace

                                                                                                  namespace?: string;

                                                                                                    property offsetVal

                                                                                                    offsetVal: number;

                                                                                                      property orders

                                                                                                      orders: Order[];

                                                                                                        property scope

                                                                                                        scope?: Transaction | Datastore;

                                                                                                          property selectVal

                                                                                                          selectVal: {}[];

                                                                                                            property startVal

                                                                                                            startVal: any;

                                                                                                              method end

                                                                                                              end: (end: string | Buffer) => this;
                                                                                                              • Set an ending cursor to a query.

                                                                                                                Parameter cursorToken

                                                                                                                The ending cursor token.

                                                                                                                Returns

                                                                                                                {Query}

                                                                                                                Example 1

                                                                                                                const {Datastore} = require('@google-cloud/datastore'); const datastore = new Datastore(); const companyQuery = datastore.createQuery('Company');

                                                                                                                const cursorToken = 'X';

                                                                                                                // Retrieve results limited to the extent of cursorToken. const endQuery = companyQuery.end(cursorToken);

                                                                                                                See Also

                                                                                                              method filter

                                                                                                              filter: {
                                                                                                              (property: string, value: {}): Query;
                                                                                                              (property: string, operator: Operator, value: {}): Query;
                                                                                                              };

                                                                                                                method groupBy

                                                                                                                groupBy: (fieldNames: string | string[]) => this;
                                                                                                                • Group query results by a list of properties.

                                                                                                                  Parameter properties

                                                                                                                  Properties to group by.

                                                                                                                  Returns

                                                                                                                  {Query}

                                                                                                                  Example 1

                                                                                                                  const {Datastore} = require('@google-cloud/datastore'); const datastore = new Datastore(); const companyQuery = datastore.createQuery('Company'); const groupedQuery = companyQuery.groupBy(['name', 'size']);

                                                                                                                method hasAncestor

                                                                                                                hasAncestor: (key: any) => this;

                                                                                                                method limit

                                                                                                                limit: (n: number) => this;
                                                                                                                • Set a limit on a query.

                                                                                                                  Parameter n

                                                                                                                  The number of results to limit the query to.

                                                                                                                  Returns

                                                                                                                  {Query}

                                                                                                                  Example 1

                                                                                                                  const {Datastore} = require('@google-cloud/datastore'); const datastore = new Datastore(); const companyQuery = datastore.createQuery('Company');

                                                                                                                  // Limit the results to 10 entities. const limitQuery = companyQuery.limit(10);

                                                                                                                  See Also

                                                                                                                method offset

                                                                                                                offset: (n: number) => this;
                                                                                                                • Set an offset on a query.

                                                                                                                  Parameter n

                                                                                                                  The offset to start from after the start cursor.

                                                                                                                  Returns

                                                                                                                  {Query}

                                                                                                                  Example 1

                                                                                                                  const {Datastore} = require('@google-cloud/datastore'); const datastore = new Datastore(); const companyQuery = datastore.createQuery('Company');

                                                                                                                  // Start from the 101st result. const offsetQuery = companyQuery.offset(100);

                                                                                                                  See Also

                                                                                                                method order

                                                                                                                order: (property: string, options?: OrderOptions) => this;
                                                                                                                • Sort the results by a property name in ascending or descending order. By default, an ascending sort order will be used.

                                                                                                                  Parameter property

                                                                                                                  The property to order by.

                                                                                                                  Parameter options

                                                                                                                  Options object.

                                                                                                                  Parameter

                                                                                                                  {boolean} [options.descending=false] Sort the results by a property name in descending order.

                                                                                                                  Returns

                                                                                                                  {Query}

                                                                                                                  Example 1

                                                                                                                  const {Datastore} = require('@google-cloud/datastore'); const datastore = new Datastore(); const companyQuery = datastore.createQuery('Company');

                                                                                                                  // Sort by size ascendingly. const companiesAscending = companyQuery.order('size');

                                                                                                                  // Sort by size descendingly. const companiesDescending = companyQuery.order('size', { descending: true });

                                                                                                                  See Also

                                                                                                                method run

                                                                                                                run: {
                                                                                                                (options?: RunQueryOptions): Promise<RunQueryResponse>;
                                                                                                                (options: RunQueryOptions, callback: RunQueryCallback): void;
                                                                                                                (callback: RunQueryCallback): void;
                                                                                                                };

                                                                                                                  method runStream

                                                                                                                  runStream: (options?: RunQueryStreamOptions) => any;
                                                                                                                  • Run the query as a readable object stream.

                                                                                                                    Query#runStream

                                                                                                                    Parameter options

                                                                                                                    Optional configuration. See Query#run for a complete list of options.

                                                                                                                    Returns

                                                                                                                    {stream}

                                                                                                                    Example 1

                                                                                                                    const {Datastore} = require('@google-cloud/datastore'); const datastore = new Datastore(); const query = datastore.createQuery('Company');

                                                                                                                    query.runStream() .on('error', console.error) .on('data', function (entity) { // Access the Key object for this entity. const key = entity[datastore.KEY]; }) .on('info', (info) => {}) .on('end', () => { // All entities retrieved. });

                                                                                                                    //- // If you anticipate many results, you can end a stream early to prevent // unnecessary processing and API requests. //- query.runStream() .on('data', function (entity) { this.end(); });

                                                                                                                  method select

                                                                                                                  select: (fieldNames: string | string[]) => this;
                                                                                                                  • Retrieve only select properties from the matched entities.

                                                                                                                    Queries that select a subset of properties are called Projection Queries.

                                                                                                                    Parameter fieldNames

                                                                                                                    Properties to return from the matched entities.

                                                                                                                    Returns

                                                                                                                    {Query}

                                                                                                                    Example 1

                                                                                                                    const {Datastore} = require('@google-cloud/datastore'); const datastore = new Datastore(); const companyQuery = datastore.createQuery('Company');

                                                                                                                    // Only retrieve the name property. const selectQuery = companyQuery.select('name');

                                                                                                                    // Only retrieve the name and size properties. const selectQuery = companyQuery.select(['name', 'size']);

                                                                                                                    See Also

                                                                                                                  method start

                                                                                                                  start: (start: string | Buffer) => this;
                                                                                                                  • Set a starting cursor to a query.

                                                                                                                    Parameter cursorToken

                                                                                                                    The starting cursor token.

                                                                                                                    Returns

                                                                                                                    {Query}

                                                                                                                    Example 1

                                                                                                                    const {Datastore} = require('@google-cloud/datastore'); const datastore = new Datastore(); const companyQuery = datastore.createQuery('Company');

                                                                                                                    const cursorToken = 'X';

                                                                                                                    // Retrieve results starting from cursorToken. const startQuery = companyQuery.start(cursorToken);

                                                                                                                    See Also

                                                                                                                  class Transaction

                                                                                                                  class Transaction extends DatastoreRequest {}
                                                                                                                  • A transaction is a set of Datastore operations on one or more entities. Each transaction is guaranteed to be atomic, which means that transactions are never partially applied. Either all of the operations in the transaction are applied, or none of them are applied.

                                                                                                                    Parameter datastore

                                                                                                                    A Datastore instance. module:datastore/request

                                                                                                                    Example 1

                                                                                                                    const {Datastore} = require('@google-cloud/datastore'); const datastore = new Datastore(); const transaction = datastore.transaction();

                                                                                                                    See Also

                                                                                                                  constructor

                                                                                                                  constructor(datastore: Datastore, options?: TransactionOptions);

                                                                                                                    property modifiedEntities_

                                                                                                                    modifiedEntities_: ModifiedEntities;

                                                                                                                      property namespace

                                                                                                                      namespace?: string;

                                                                                                                        property readOnly

                                                                                                                        readOnly: boolean;

                                                                                                                          property request

                                                                                                                          request: Function;

                                                                                                                            property skipCommit

                                                                                                                            skipCommit?: boolean;

                                                                                                                              method commit

                                                                                                                              commit: {
                                                                                                                              (gaxOptions?: any): Promise<CommitResponse>;
                                                                                                                              (callback: CommitCallback): void;
                                                                                                                              (gaxOptions: any, callback: CommitCallback): void;
                                                                                                                              };

                                                                                                                                method createQuery

                                                                                                                                createQuery: {
                                                                                                                                (kind?: string): Query;
                                                                                                                                (kind?: string[]): Query;
                                                                                                                                (namespace: string, kind: string): Query;
                                                                                                                                (namespace: string, kind: string[]): Query;
                                                                                                                                };

                                                                                                                                  method delete

                                                                                                                                  delete: (entities?: Entities) => any;
                                                                                                                                  • Delete all entities identified with the specified key(s) in the current transaction.

                                                                                                                                    Parameter key

                                                                                                                                    Datastore key object(s).

                                                                                                                                    Example 1

                                                                                                                                    const {Datastore} = require('@google-cloud/datastore'); const datastore = new Datastore(); const transaction = datastore.transaction();

                                                                                                                                    transaction.run((err) => { if (err) { // Error handling omitted. }

                                                                                                                                    // Delete a single entity. transaction.delete(datastore.key(['Company', 123]));

                                                                                                                                    // Delete multiple entities at once. transaction.delete([ datastore.key(['Company', 123]), datastore.key(['Product', 'Computer']) ]);

                                                                                                                                    transaction.commit((err) => { if (!err) { // Transaction committed successfully. } }); });

                                                                                                                                  method insert

                                                                                                                                  insert: (entities: Entities) => void;
                                                                                                                                  • Maps to Datastore#save, forcing the method to be insert.

                                                                                                                                    Parameter entities

                                                                                                                                    Datastore key object(s).

                                                                                                                                    Parameter

                                                                                                                                    {Key} entities.key Datastore key object.

                                                                                                                                    Parameter

                                                                                                                                    {string[]} [entities.excludeFromIndexes] Exclude properties from indexing using a simple JSON path notation. See the examples in Datastore#save to see how to target properties at different levels of nesting within your entity.

                                                                                                                                    Parameter

                                                                                                                                    {object} entities.data Data to save with the provided key.

                                                                                                                                  method rollback

                                                                                                                                  rollback: {
                                                                                                                                  (callback: RollbackCallback): void;
                                                                                                                                  (gaxOptions?: any): Promise<RollbackResponse>;
                                                                                                                                  (gaxOptions: any, callback: RollbackCallback): void;
                                                                                                                                  };

                                                                                                                                    method run

                                                                                                                                    run: {
                                                                                                                                    (options?: RunOptions): Promise<RunResponse>;
                                                                                                                                    (callback: RunCallback): void;
                                                                                                                                    (options: RunOptions, callback: RunCallback): void;
                                                                                                                                    };

                                                                                                                                      method save

                                                                                                                                      save: (entities: Entities) => void;
                                                                                                                                      • Insert or update the specified object(s) in the current transaction. If a key is incomplete, its associated object is inserted and the original Key object is updated to contain the generated ID.

                                                                                                                                        This method will determine the correct Datastore method to execute (upsert, insert, or update) by using the key(s) provided. For example, if you provide an incomplete key (one without an ID), the request will create a new entity and have its ID automatically assigned. If you provide a complete key, the entity will be updated with the data specified.

                                                                                                                                        By default, all properties are indexed. To prevent a property from being included in *all* indexes, you must supply an excludeFromIndexes array. See below for an example.

                                                                                                                                        Parameter entities

                                                                                                                                        Datastore key object(s).

                                                                                                                                        Parameter

                                                                                                                                        {Key} entities.key Datastore key object.

                                                                                                                                        Parameter

                                                                                                                                        {string[]} [entities.excludeFromIndexes] Exclude properties from indexing using a simple JSON path notation. See the example below to see how to target properties at different levels of nesting within your entity.

                                                                                                                                        Parameter

                                                                                                                                        {object} entities.data Data to save with the provided key.

                                                                                                                                        Example 1

                                                                                                                                        Save a single entity. const {Datastore} = require('@google-cloud/datastore'); const datastore = new Datastore(); const transaction = datastore.transaction();

                                                                                                                                        // Notice that we are providing an incomplete key. After the transaction is // committed, the Key object held by the key variable will be populated // with a path containing its generated ID. //- const key = datastore.key('Company');

                                                                                                                                        transaction.run((err) => { if (err) { // Error handling omitted. }

                                                                                                                                        transaction.save({ key: key, data: { rating: '10' } });

                                                                                                                                        transaction.commit((err) => { if (!err) { // Data saved successfully. } }); });

                                                                                                                                        Example 2

                                                                                                                                        const {Datastore} = require('@google-cloud/datastore'); const datastore = new Datastore(); const transaction = datastore.transaction();

                                                                                                                                        // Use an array, excludeFromIndexes, to exclude properties from indexing. // This will allow storing string values larger than 1500 bytes.

                                                                                                                                        transaction.run((err) => { if (err) { // Error handling omitted. }

                                                                                                                                        transaction.save({ key: key, excludeFromIndexes: [ 'description', 'embeddedEntity.description', 'arrayValue[].description' ], data: { description: 'Long string (...)', embeddedEntity: { description: 'Long string (...)' }, arrayValue: [ { description: 'Long string (...)' } ] } });

                                                                                                                                        transaction.commit((err) => { if (!err) { // Data saved successfully. } }); });

                                                                                                                                        Example 3

                                                                                                                                        Save multiple entities at once. const {Datastore} = require('@google-cloud/datastore'); const datastore = new Datastore(); const transaction = datastore.transaction(); const companyKey = datastore.key(['Company', 123]); const productKey = datastore.key(['Product', 'Computer']);

                                                                                                                                        transaction.run((err) => { if (err) { // Error handling omitted. }

                                                                                                                                        transaction.save([ { key: companyKey, data: { HQ: 'Dallas, TX' } }, { key: productKey, data: { vendor: 'Dell' } } ]);

                                                                                                                                        transaction.commit((err) => { if (!err) { // Data saved successfully. } }); });

                                                                                                                                      method update

                                                                                                                                      update: (entities: Entities) => void;
                                                                                                                                      • Maps to Datastore#save, forcing the method to be update.

                                                                                                                                        Parameter entities

                                                                                                                                        Datastore key object(s).

                                                                                                                                        Parameter

                                                                                                                                        {Key} entities.key Datastore key object.

                                                                                                                                        Parameter

                                                                                                                                        {string[]} [entities.excludeFromIndexes] Exclude properties from indexing using a simple JSON path notation. See the examples in Datastore#save to see how to target properties at different levels of nesting within your entity.

                                                                                                                                        Parameter

                                                                                                                                        {object} entities.data Data to save with the provided key.

                                                                                                                                      method upsert

                                                                                                                                      upsert: (entities: Entities) => void;
                                                                                                                                      • Maps to Datastore#save, forcing the method to be upsert.

                                                                                                                                        Parameter entities

                                                                                                                                        Datastore key object(s).

                                                                                                                                        Parameter

                                                                                                                                        {Key} entities.key Datastore key object.

                                                                                                                                        Parameter

                                                                                                                                        {string[]} [entities.excludeFromIndexes] Exclude properties from indexing using a simple JSON path notation. See the examples in Datastore#save to see how to target properties at different levels of nesting within your entity.

                                                                                                                                        Parameter

                                                                                                                                        {object} entities.data Data to save with the provided key.

                                                                                                                                      Interfaces

                                                                                                                                      interface BooleanObject

                                                                                                                                      interface BooleanObject {}

                                                                                                                                        index signature

                                                                                                                                        [key: string]: boolean;

                                                                                                                                          interface DatastoreOptions

                                                                                                                                          interface DatastoreOptions extends GoogleAuthOptions {}

                                                                                                                                            property apiEndpoint

                                                                                                                                            apiEndpoint?: string;

                                                                                                                                              property namespace

                                                                                                                                              namespace?: string;

                                                                                                                                                property sslCreds

                                                                                                                                                sslCreds?: ChannelCredentials;

                                                                                                                                                  interface EntityProtoReduceAccumulator

                                                                                                                                                  interface EntityProtoReduceAccumulator {}

                                                                                                                                                    index signature

                                                                                                                                                    [key: string]: ValueProto;

                                                                                                                                                      interface EntityProtoReduceData

                                                                                                                                                      interface EntityProtoReduceData {}

                                                                                                                                                        property excludeFromIndexes

                                                                                                                                                        excludeFromIndexes: ValueProto;

                                                                                                                                                          property name

                                                                                                                                                          name: string | number;

                                                                                                                                                            property value

                                                                                                                                                            value: ValueProto;

                                                                                                                                                              interface ExportEntitiesConfig

                                                                                                                                                              interface ExportEntitiesConfig
                                                                                                                                                              extends Omit<google.datastore.admin.v1.IExportEntitiesRequest, 'projectId'> {}

                                                                                                                                                                property bucket

                                                                                                                                                                bucket?:
                                                                                                                                                                | string
                                                                                                                                                                | {
                                                                                                                                                                name: string;
                                                                                                                                                                };

                                                                                                                                                                  property gaxOptions

                                                                                                                                                                  gaxOptions?: CallOptions;

                                                                                                                                                                    property kinds

                                                                                                                                                                    kinds?: string[];

                                                                                                                                                                      property namespaces

                                                                                                                                                                      namespaces?: string[];

                                                                                                                                                                        interface ImportEntitiesConfig

                                                                                                                                                                        interface ImportEntitiesConfig
                                                                                                                                                                        extends Omit<google.datastore.admin.v1.IImportEntitiesRequest, 'projectId'> {}

                                                                                                                                                                          property file

                                                                                                                                                                          file?:
                                                                                                                                                                          | string
                                                                                                                                                                          | {
                                                                                                                                                                          bucket: {
                                                                                                                                                                          name: string;
                                                                                                                                                                          };
                                                                                                                                                                          name: string;
                                                                                                                                                                          };

                                                                                                                                                                            property gaxOptions

                                                                                                                                                                            gaxOptions?: CallOptions;

                                                                                                                                                                              property kinds

                                                                                                                                                                              kinds?: string[];

                                                                                                                                                                                property namespaces

                                                                                                                                                                                namespaces?: string[];

                                                                                                                                                                                  interface KeyToLegacyUrlSafeCallback

                                                                                                                                                                                  interface KeyToLegacyUrlSafeCallback {}

                                                                                                                                                                                    call signature

                                                                                                                                                                                    (err?: Error | null, urlSafeKey?: string): void;

                                                                                                                                                                                      interface LongRunningCallback

                                                                                                                                                                                      interface LongRunningCallback {}

                                                                                                                                                                                        call signature

                                                                                                                                                                                        (
                                                                                                                                                                                        err: ServiceError | null,
                                                                                                                                                                                        operation?: Operation,
                                                                                                                                                                                        apiResponse?: google.longrunning.IOperation
                                                                                                                                                                                        ): void;

                                                                                                                                                                                          interface TransactionOptions

                                                                                                                                                                                          interface TransactionOptions {}

                                                                                                                                                                                            property id

                                                                                                                                                                                            id?: string;

                                                                                                                                                                                              property readOnly

                                                                                                                                                                                              readOnly?: boolean;

                                                                                                                                                                                                Type Aliases

                                                                                                                                                                                                type Entity

                                                                                                                                                                                                type Entity = any;

                                                                                                                                                                                                  type InsertCallback

                                                                                                                                                                                                  type InsertCallback = CommitCallback;

                                                                                                                                                                                                    type InsertResponse

                                                                                                                                                                                                    type InsertResponse = CommitResponse;

                                                                                                                                                                                                      type LongRunningResponse

                                                                                                                                                                                                      type LongRunningResponse = [Operation, google.longrunning.IOperation];

                                                                                                                                                                                                        type PathType

                                                                                                                                                                                                        type PathType = string | number | entity.Int;

                                                                                                                                                                                                          type UpdateCallback

                                                                                                                                                                                                          type UpdateCallback = CommitCallback;

                                                                                                                                                                                                            type UpdateResponse

                                                                                                                                                                                                            type UpdateResponse = CommitResponse;

                                                                                                                                                                                                              type UpsertCallback

                                                                                                                                                                                                              type UpsertCallback = CommitCallback;

                                                                                                                                                                                                                type UpsertResponse

                                                                                                                                                                                                                type UpsertResponse = CommitResponse;

                                                                                                                                                                                                                  Package Files (6)

                                                                                                                                                                                                                  Dependencies (8)

                                                                                                                                                                                                                  Dev Dependencies (24)

                                                                                                                                                                                                                  Peer Dependencies (0)

                                                                                                                                                                                                                  No peer dependencies.

                                                                                                                                                                                                                  Badge

                                                                                                                                                                                                                  To add a badge like this onejsDocs.io badgeto your package's README, use the codes available below.

                                                                                                                                                                                                                  You may also use Shields.io to create a custom badge linking to https://www.jsdocs.io/package/@google-cloud/datastore.

                                                                                                                                                                                                                  • Markdown
                                                                                                                                                                                                                    [![jsDocs.io](https://img.shields.io/badge/jsDocs.io-reference-blue)](https://www.jsdocs.io/package/@google-cloud/datastore)
                                                                                                                                                                                                                  • HTML
                                                                                                                                                                                                                    <a href="https://www.jsdocs.io/package/@google-cloud/datastore"><img src="https://img.shields.io/badge/jsDocs.io-reference-blue" alt="jsDocs.io"></a>