Constructor

DatastoreRequest

new 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.

Methods

allocateIds

allocateIds(key, options, callback)

Generate IDs without creating entities.

Parameter

key

Key

The key object to complete.

options

(number or object)

Either the number of IDs to allocate or an options object for further customization of the request.

Values in options have the following properties:

Parameter

allocations

number

How many IDs to allocate.

gaxOptions

Optional

object

Request configuration options, outlined here: https://googleapis.github.io/gax-nodejs/global.html#CallOptions.

callback

function()

The callback function.

Values in callback have the following properties:

Parameter

err

error

An error returned while making this request

Value may be null.

keys

array

The generated IDs

apiResponse

object

The full API response.

Example

var incompleteKey = datastore.key(['Company']);

//-
// The following call will create 100 new IDs from the Company kind, which
// exists under the default namespace.
//-
datastore.allocateIds(incompleteKey, 100, function(err, keys) {});

//-
// Or, if you're using a transaction object.
//-
var transaction = datastore.transaction();

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

  transaction.allocateIds(incompleteKey, 100, function(err, keys) {
    if (err) {
      // Error handling omitted.
    }

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

//-
// You may prefer to create IDs from a non-default namespace by providing an
// incomplete key with a namespace. Similar to the previous example, the call
// below will create 100 new IDs, but from the Company kind that exists under
// the "ns-test" namespace.
//-
var incompleteKey = datastore.key({
  namespace: 'ns-test',
  path: ['Company']
});

function callback(err, keys, apiResponse) {}

datastore.allocateIds(incompleteKey, 100, callback);

//-
// If the callback is omitted, we'll return a Promise.
//-
datastore.allocateIds(incompleteKey, 100).then(function(data) {
  var keys = data[0];
  var apiResponse = data[1];
});

createReadStream

createReadStream(keys, options)

Retrieve the entities as a readable object stream.

Parameter

keys

(Key or Array of Key)

Datastore key object(s).

options

Optional

object

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

Throws

Error 

If at least one Key object is not provided.

Example

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

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

delete

delete(key, gaxOptions, callback)

Delete all entities identified with the specified key(s).

Parameter

key

(Key or Array of Key)

Datastore key object(s).

gaxOptions

Optional

object

Request configuration options, outlined here: https://googleapis.github.io/gax-nodejs/global.html#CallOptions.

callback

function()

The callback function.

Values in callback have the following properties:

Parameter

err

error

An error returned while making this request

Value may be null.

apiResponse

object

The full API response.

Example

var key = datastore.key(['Company', 123]);
datastore.delete(key, function(err, apiResp) {});

//-
// Or, if you're using a transaction object.
//-
var transaction = datastore.transaction();

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

  transaction.delete(key);

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

//-
// Delete multiple entities at once.
//-
datastore.delete([
  datastore.key(['Company', 123]),
  datastore.key(['Product', 'Computer'])
], function(err, apiResponse) {});

//-
// If the callback is omitted, we'll return a Promise.
//-
datastore.delete().then(function(data) {
  var apiResponse = data[0];
});

get

get(keys, options, callback)

Retrieve the entities identified with the specified key(s) in the current transaction. Get operations require a valid key to retrieve the key-identified entity from Datastore.

Parameter

keys

(Key or Array of Key)

Datastore key object(s).

options

Optional

object

Optional configuration.

Values in options have the following properties:

Parameter

consistency

Optional

string

Specify either strong or eventual. If not specified, default values are chosen by Datastore for the operation. Learn more about strong and eventual consistency here.

gaxOptions

Optional

object

Request configuration options, outlined here: https://googleapis.github.io/gax-nodejs/global.html#CallOptions.

callback

function()

The callback function.

Values in callback have the following properties:

Parameter

err

error

An error returned while making this request

Value may be null.

entity

(object or Array of object)

The entity object(s) which match the provided keys.

Throws

Error 

If at least one Key object is not provided.

Example

//-
// Get a single entity.
//-
var key = datastore.key(['Company', 123]);

datastore.get(key, function(err, entity) {});

//-
// Or, if you're using a transaction object.
//-
var transaction = datastore.transaction();

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

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

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

//-
// Get multiple entities at once with a callback.
//-
var keys = [
  datastore.key(['Company', 123]),
  datastore.key(['Product', 'Computer'])
];

datastore.get(keys, function(err, entities) {});

//-
// Here's how you would update the value of an entity with the help of the
// `save` method.
//-
datastore.get(key, function(err, entity) {
  if (err) {
    // Error handling omitted.
  }

  entity.newValue = true;

  datastore.save({
    key: key,
    data: entity
  }, function(err) {});
});

//-
// If the callback is omitted, we'll return a Promise.
//-
datastore.get(keys).then(function(data) {
  var entities = data[0];
});

insert

insert(entities, callback)

Maps to Datastore#save, forcing the method to be insert.

Parameter

entities

(object or Array of object)

Datastore key object(s).

Values in entities have the following properties:

Parameter

key

Key

Datastore key object.

excludeFromIndexes

Optional

Array of string

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.

data

object

Data to save with the provided key.

callback

function()

The callback function.

Values in callback have the following properties:

Parameter

err

error

An error returned while making this request

Value may be null.

apiResponse

object

The full API response.

runQuery

runQuery(query, options, callback)

Datastore allows you to query entities by kind, filter them by property filters, and sort them by a property name. Projection and pagination are also supported.

The query is run, and the results are returned as the second argument to your callback. A third argument may also exist, which is a query object that uses the end cursor from the previous query as the starting cursor for the next query. You can pass that object back to this method to see if more results exist.

Parameter

query

Query

Query object.

options

Optional

object

Optional configuration.

Values in options have the following properties:

Parameter

consistency

Optional

string

Specify either strong or eventual. If not specified, default values are chosen by Datastore for the operation. Learn more about strong and eventual consistency here.

gaxOptions

Optional

object

Request configuration options, outlined here: https://googleapis.github.io/gax-nodejs/global.html#CallOptions.

callback

Optional

function()

The callback function. If omitted, a readable stream instance is returned.

Values in callback have the following properties:

Parameter

err

error

An error returned while making this request

Value may be null.

entities

Array of object

A list of entities.

info

object

An object useful for pagination.

info.endCursor

string

Use this in a follow-up query to begin from where these results ended.

Value may be null.

info.moreResults

string

Datastore responds with one of:

- Datastore#MORE\_RESULTS\_AFTER\_LIMIT: There *may* be more
  results after the specified limit.
- Datastore#MORE\_RESULTS\_AFTER\_CURSOR: There *may* be more
  results after the specified end cursor.
- Datastore#NO\_MORE\_RESULTS: There are no more results.

Example

//-
// Where you see `transaction`, assume this is the context that's relevant to
// your use, whether that be a Datastore or a Transaction object.
//-
var query = datastore.createQuery('Lion');

datastore.runQuery(query, function(err, entities, info) {
  // entities = An array of records.

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

//-
// Or, if you're using a transaction object.
//-
var transaction = datastore.transaction();

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

  transaction.runQuery(query, function(err, entities) {
    if (err) {
      // Error handling omitted.
    }

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

//-
// A keys-only query returns just the keys of the result entities instead of
// the entities themselves, at lower latency and cost.
//-
var keysOnlyQuery = datastore.createQuery('Lion').select('__key__');

datastore.runQuery(keysOnlyQuery, function(err, entities) {
  var keys = entities.map(function(entity) {
    return entity[datastore.KEY];
  });
});

//-
// If the callback is omitted, we'll return a Promise.
//-
datastore.runQuery(query).then(function(data) {
  var entities = data[0];
});

runQueryStream

runQueryStream(query, options)

Get a list of entities as a readable object stream.

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

Parameter

query

Query

Query object.

options

Optional

object

Optional configuration.

Values in options have the following properties:

Parameter

gaxOptions

Optional

object

Request configuration options, outlined here: https://googleapis.github.io/gax-nodejs/global.html#CallOptions.

Example

datastore.runQueryStream(query)
  .on('error', console.error)
  .on('data', function(entity) {
    // Access the Key object for this entity.
    var key = entity[datastore.KEY];
  })
  .on('info', function(info) {})
  .on('end', function() {
    // 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', function(entity) {
    this.end();
  });

save

save(entities, gaxOptions, callback)

Insert or update the specified object(s). 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

(object or Array of object)

Datastore key object(s).

Values in entities have the following properties:

Parameter

key

Key

Datastore key object.

excludeFromIndexes

Optional

Array of string

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

method

Optional

string

Explicit method to use, either 'insert', 'update', or 'upsert'.

data

object

Data to save with the provided key. entity.

gaxOptions

Optional

object

Request configuration options, outlined here: https://googleapis.github.io/gax-nodejs/global.html#CallOptions.

callback

function()

The callback function.

Values in callback have the following properties:

Parameter

err

error

An error returned while making this request

Value may be null.

apiResponse

object

The full API response.

Throws

Error 

If an unrecognized method is provided.

Example

//-
// Save a single entity.
//
// Notice that we are providing an incomplete key. After saving, the original
// Key object used to save will be updated to contain the path with its
// generated ID.
//-
var key = datastore.key('Company');
var entity = {
  key: key,
  data: {
    rating: '10'
  }
};

datastore.save(entity, function(err) {
  console.log(key.path); // [ 'Company', 5669468231434240 ]
  console.log(key.namespace); // undefined
});

//-
// Save a single entity using a provided name instead of auto-generated ID.
//
// Here we are providing a key with name instead of an ID. After saving, the
// original Key object used to save will be updated to contain the path with
// the name instead of a generated ID.
//-
var key = datastore.key(['Company', 'donutshack']);
var entity = {
  key: key,
  data: {
    name: 'DonutShack',
    rating: 8
  }
};

datastore.save(entity, function(err) {
  console.log(key.path); // ['Company', 'donutshack']
  console.log(key.namespace); // undefined
});

//-
// Save a single entity with a provided namespace. Namespaces allow for
// multitenancy. To read more about this, see
// [the Datastore docs on key concepts](https://goo.gl/M1LUAu).
//
// Here we are providing a key with namespace.
//-
var key = datastore.key({
  namespace: 'my-namespace',
  path: ['Company', 'donutshack']
});

var entity = {
  key: key,
  data: {
    name: 'DonutShack',
    rating: 8
  }
};

datastore.save(entity, function(err) {
  console.log(key.path); // ['Company', 'donutshack']
  console.log(key.namespace); // 'my-namespace'
});

//-
// Save different types of data, including ints, doubles, dates, booleans,
// blobs, and lists.
//
// Notice that we are providing an incomplete key. After saving, the original
// Key object used to save will be updated to contain the path with its
// generated ID.
//-
var key = datastore.key('Company');
var entity = {
  key: key,
  data: {
    name: 'DonutShack',
    rating: datastore.int(10),
    worth: datastore.double(123456.78),
    location: datastore.geoPoint({
      latitude: 40.6894,
      longitude: -74.0447
    }),
    numDonutsServed: 45,
    founded: new Date('Tue May 12 2015 15:30:00 GMT-0400 (EDT)'),
    isStartup: true,
    donutEmoji: new Buffer('\uD83C\uDF69'),
    keywords: [
      'donut',
      'coffee',
      'yum'
    ]
  }
};

datastore.save(entity, function(err, apiResponse) {});

//-
// Use an array, `excludeFromIndexes`, to exclude properties from indexing.
// This will allow storing string values larger than 1500 bytes.
//-
var entity = {
  key: datastore.key('Company'),
  excludeFromIndexes: [
    'description',
    'embeddedEntity.description',
    'arrayValue[]',
    'arrayValue[].description'
  ],
  data: {
    description: 'Long string (...)',
    embeddedEntity: {
      description: 'Long string (...)'
    },
    arrayValue: [
      'Long string (...)',
      {
        description: 'Long string (...)'
      }
    ]
  }
};

datastore.save(entity, function(err, apiResponse) {});

//-
// Save multiple entities at once.
//-
var companyKey = datastore.key(['Company', 123]);
var productKey = datastore.key(['Product', 'Computer']);
var entities = [
  {
    key: companyKey,
    data: {
      HQ: 'Dallas, TX'
    }
  },
  {
    key: productKey,
    data: {
      vendor: 'Dell'
    }
  }
];

datastore.save(entities, function(err, apiResponse) {});

//-
// Explicitly attempt to 'insert' a specific entity.
//-
var userKey = datastore.key(['User', 'chilts']);
var entity = {
  key: userKey,
  method: 'insert',
  data: {
    fullName: 'Andrew Chilton'
  }
};

datastore.save(entity, function(err, apiResponse) {});

//-
// If the callback is omitted, we'll return a Promise.
//-
datastore.save(entity).then(function(data) {
  var apiResponse = data[0];
});

update

update(entities, callback)

Maps to Datastore#save, forcing the method to be update.

Parameter

entities

(object or Array of object)

Datastore key object(s).

Values in entities have the following properties:

Parameter

key

Key

Datastore key object.

excludeFromIndexes

Optional

Array of string

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.

data

object

Data to save with the provided key.

callback

function()

The callback function.

Values in callback have the following properties:

Parameter

err

error

An error returned while making this request

Value may be null.

apiResponse

object

The full API response.

upsert

upsert(entities, callback)

Maps to Datastore#save, forcing the method to be upsert.

Parameter

entities

(object or Array of object)

Datastore key object(s).

Values in entities have the following properties:

Parameter

key

Key

Datastore key object.

excludeFromIndexes

Optional

Array of string

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.

data

object

Data to save with the provided key.

callback

function()

The callback function.

Values in callback have the following properties:

Parameter

err

error

An error returned while making this request

Value may be null.

apiResponse

object

The full API response.