DatastoreRequest class.
Datastore.DatastoreRequest
DatastoreRequest
Query class.
Datastore.Query
Query
Transaction class.
Datastore.Transaction
Transaction
Optional
baseOptional
customOptional
namespaceOptional
port_Static
KEYAccess the Key from an Entity object.
Datastore#KEY
Static
MORE_Static
MORE_Static
NO_Generate IDs without creating entities.
The key object to complete.
Either the number of IDs to allocate or an options object for further customization of the request.
const 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, (err, keys) => {});
//-
// Or, if you're using a transaction object.
//-
const transaction = datastore.transaction();
transaction.run((err) => {
if (err) {
// Error handling omitted.
}
transaction.allocateIds(incompleteKey, 100, (err, keys) => {
if (err) {
// Error handling omitted.
}
transaction.commit((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.
//-
const incompleteKey = datastore.key({
namespace: 'ns-test',
path: ['Company']
});
function callback(err, keys, apiResponse) {}
datastore.allocateIds(incompleteKey, 100, callback);
//-
// Returns a Promise if callback is omitted.
//-
datastore.allocateIds(incompleteKey, 100).then((data) => {
const keys = data[0];
const apiResponse = data[1];
});
Create an aggregation query from a Query.
A Query object.
Create a query for the specified kind. See Query for all of the available methods.
Optional
kind: stringThe kind to query.
const {Datastore} = require('@google-cloud/datastore');
const datastore = new Datastore();
const query = datastore.createQuery('Company');
Optional
kind: string[]Retrieve the entities as a readable object stream.
Datastore key object(s).
Optional
options: RunQueryOptionsOptional configuration. See get for a complete list of options.
If at least one Key object is not provided.
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.
});
Delete all entities identified with the specified key(s).
Optional
gaxOptions: CallOptionsRequest configuration options, outlined here: https://googleapis.github.io/gax-nodejs/global.html#CallOptions.
const key = datastore.key(['Company', 123]);
datastore.delete(key, (err, apiResp) => {});
//-
// Or, if you're using a transaction object.
//-
const transaction = datastore.transaction();
transaction.run((err) => {
if (err) {
// Error handling omitted.
}
transaction.delete(key);
transaction.commit((err) => {
if (!err) {
// Transaction committed successfully.
}
});
});
//-
// Delete multiple entities at once.
//-
datastore.delete([
datastore.key(['Company', 123]),
datastore.key(['Product', 'Computer'])
], (err, apiResponse) => {});
//-
// Returns a Promise if callback is omitted.
//-
datastore.delete().then((data) => {
const apiResponse = data[0];
});
Private
determinePrivate
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.
Optional
customApiEndpoint: stringCustom API endpoint.
Export entities from this project to a Google Cloud Storage bucket.
Configuration object.
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.
If at least one Key object is not provided.
//-
// Get a single entity.
//-
const key = datastore.key(['Company', 123]);
datastore.get(key, (err, entity) => {});
//-
// Or, if you're using a transaction object.
//-
const transaction = datastore.transaction();
transaction.run((err) => {
if (err) {
// Error handling omitted.
}
transaction.get(key, (err, entity) => {
if (err) {
// Error handling omitted.
}
transaction.commit((err) => {
if (!err) {
// Transaction committed successfully.
}
});
});
});
//-
// Get multiple entities at once with a callback.
//-
const keys = [
datastore.key(['Company', 123]),
datastore.key(['Product', 'Computer'])
];
datastore.get(keys, (err, entities) => {});
//-
// Below is how to update the value of an entity with the help of the
// `save` method.
//-
datastore.get(key, (err, entity) => {
if (err) {
// Error handling omitted.
}
entity.newValue = true;
datastore.save({
key: key,
data: entity
}, (err) => {});
});
//-
// Returns a Promise if callback is omitted.
//-
datastore.get(keys).then((data) => {
const entities = data[0];
});
Get all of the indexes in this project.
Optional
options: GetIndexesOptionsGet all of the indexes in this project as a readable object stream.
Optional
options: GetIndexesOptionsConfiguration object. See getIndexes for a complete list of options.
Import entities into this project from a remote file.
Configuration object.
Maps to save, forcing the method to be insert
.
Datastore key object(s).
Helper to create a Key object, scoped to the instance's namespace by default.
You may also specify a configuration object to define a namespace and path.
Optional
options: KeyOptionsKey path. To specify or override a namespace, you must use an object here to explicitly state it.
A newly created Key from the options given.
<caption>Create an incomplete key with a kind value of `Company`.
Since no Id is supplied, Datastore will generate one on save.</caption>
const {Datastore} = require('@google-cloud/datastore');
const datastore = new Datastore();
const key = datastore.key('Company');
<caption>Create a complete key with a kind value of `Company` and Id `123`.</caption>
const {Datastore} = require('@google-cloud/datastore');
const datastore = new Datastore();
const key = datastore.key(['Company', 123]);
<caption>If the ID integer is outside the bounds of a JavaScript Number
object, create an Int.</caption>
const {Datastore} = require('@google-cloud/datastore');
const datastore = new Datastore();
const key = datastore.key([
'Company',
datastore.int('100000000000001234')
]);
<caption>Create a complete key with a kind value of `Company` and name `Google`.
Because the supplied Id is a string, Datastore will prefix it with "name=".
Had the supplied Id been numeric, Datastore would prefix it with the standard, "id=".</caption>
const {Datastore} = require('@google-cloud/datastore');
const datastore = new Datastore();
const key = datastore.key(['Company', 'Google']);
<caption>Create a complete key from a provided namespace and path.</caption>
const {Datastore} = require('@google-cloud/datastore');
const datastore = new Datastore();
const key = datastore.key({
namespace: 'My-NS',
path: ['Company', 123]
});
<caption>Create a complete key that specifies an ancestor. This will create a Team entity
with a name of "Datastore", which belongs to the Company with the "name=Google" key.</caption>
const {Datastore} = require('@google-cloud/datastore');
const datastore = new Datastore();
const key = datastore.key(['Company', 'Google', 'Team', 'Datastore']);
<caption>Create a incomplete key that specifies an ancestor. This will create an Employee entity
with an auto-generated Id, which belongs to the Company with the "name=Google" key.</caption>
const {Datastore} = require('@google-cloud/datastore');
const datastore = new Datastore();
const key = datastore.key(['Company', 'Google', 'Employee']);
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").
Entity key object.
Created urlsafe key.
const {Datastore} = require('@google-cloud/datastore');
const datastore = new Datastore();
const urlSafeKey = 'ag9ncmFzcy1jbHVtcC00NzlyEwsSB0NvbXBhbnkiBkdvb2dsZQw';
datastore.keyFromLegacyUrlsafe(key);
Helper to create a URL safe key.
This is intended to work with the "legacy" representation of a datastore "Key" used within Google App Engine (a so-called "Reference"). The returned string can be used as the "urlsafe" The base64 encoded values will have padding removed.
Entity key object.
Optional
locationPrefix: stringOptional .
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.
const {Datastore} = require('@google-cloud/datastore');
const datastore = new Datastore();
const key = datastore.key(['Company', 'Google']);
datastore.keyToLegacyUrlSafe(key, (err, urlSafeKey) => {
if (err) {
// Error handling omitted.
}
console.log(urlSafeKey);
});
//-
// Create a complete URL-safe key using a location prefix.
//-
const locationPrefix = 's~';
datastore.keyToLegacyUrlSafe(key, locationPrefix, (err, urlSafeKey) => {
if (err) {
// Error handling omitted.
}
console.log(urlSafeKey);
});
//-
// If the callback is omitted, we'll return a Promise.
//-
datastore.keyToLegacyUrlSafe(key).then((data) => {
const urlSafeKey = data[0];
console.log(urlSafeKey);
});
Merge 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.
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 get the data from datastore
and merge 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.
Maps to save, forcing the method to be upsert
.
Datastore key object(s).
Private
preparePrivate
request_Optional
options: RunQueryOptionsDatastore 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.
Query object.
Optional
options: RunQueryOptionsOptional configuration.
//-
// Where you see `transaction`, assume this is the context that's relevant
to
// your use, whether that be a Datastore or a Transaction object.
//-
const query = datastore.createQuery('Lion');
datastore.runQuery(query, (err, entities, info) => {
// entities = An array of records.
// Access the Key object for an entity.
const firstEntityKey = entities[0][datastore.KEY];
});
//-
// Or, if you're using a transaction object.
//-
const transaction = datastore.transaction();
transaction.run((err) => {
if (err) {
// Error handling omitted.
}
transaction.runQuery(query, (err, entities) => {
if (err) {
// Error handling omitted.
}
transaction.commit((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.
//-
const keysOnlyQuery = datastore.createQuery('Lion').select('__key__');
datastore.runQuery(keysOnlyQuery, (err, entities) => {
const keys = entities.map((entity) => {
return entity[datastore.KEY];
});
});
//-
// Returns a Promise if callback is omitted.
//-
datastore.runQuery(query).then((data) => {
const entities = data[0];
});
Get a list of entities as a readable object stream.
See runQuery for a list of all available options.
Query object.
Optional
options: RunQueryOptionsOptional configuration.
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();
});
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.
To prevent large properties from being included in all indexes, you must supply
excludeLargeProperties: true
.
See below for an example.
Datastore key object(s).
Optional
gaxOptions: CallOptionsRequest configuration options, outlined here: https://googleapis.github.io/gax-nodejs/global.html#CallOptions.
save as save
If an unrecognized method is provided.
//-
// 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.
//-
const key = datastore.key('Company');
const entity = {
key: key,
data: {
rating: '10'
}
};
datastore.save(entity, (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.
//-
const key = datastore.key(['Company', 'donutshack']);
const entity = {
key: key,
data: {
name: 'DonutShack',
rating: 8
}
};
datastore.save(entity, (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.
//-
const key = datastore.key({
namespace: 'my-namespace',
path: ['Company', 'donutshack']
});
const entity = {
key: key,
data: {
name: 'DonutShack',
rating: 8
}
};
datastore.save(entity, (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.
//-
const key = datastore.key('Company');
const 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: Buffer.from('\uD83C\uDF69'),
keywords: [
'donut',
'coffee',
'yum'
]
}
};
datastore.save(entity, (err, apiResponse) => {});
//-
// Use an array, `excludeFromIndexes`, to exclude properties from indexing.
// This will allow storing string values larger than 1500 bytes.
//-
const 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, (err, apiResponse) => {});
//-
// Use boolean `excludeLargeProperties`, to auto exclude Large properties from indexing.
// This will allow storing string values larger than 1500 bytes.
//-
const entity = {
key: datastore.key('Company'),
data: {
description: 'Long string (...)',
embeddedEntity: {
description: 'Long string (...)'
},
arrayValue: [
'Long string (...)',
{
description: 'Long string (...)'
}
]
},
excludeLargeProperties: true
};
datastore.save(entity, (err, apiResponse) => {});
//-
// Save multiple entities at once.
//-
const companyKey = datastore.key(['Company', 123]);
const productKey = datastore.key(['Product', 'Computer']);
const entities = [
{
key: companyKey,
data: {
HQ: 'Dallas, TX'
}
},
{
key: productKey,
data: {
vendor: 'Dell'
}
}
];
datastore.save(entities, (err, apiResponse) => {});
//-
// Explicitly attempt to 'insert' a specific entity.
//-
const userKey = datastore.key(['User', 'chilts']);
const entity = {
key: userKey,
method: 'insert',
data: {
fullName: 'Andrew Chilton'
}
};
datastore.save(entity, (err, apiResponse) => {});
//-
// Returns a Promise if callback is omitted.
//-
datastore.save(entity).then((data) => {
const apiResponse = data[0];
});
Create a new Transaction object.
Optional
options: TransactionOptionsConfiguration object.
const {Datastore} = require('@google-cloud/datastore');
const datastore = new Datastore();
const transaction = datastore.transaction();
Maps to save, forcing the method to be update
.
Datastore key object(s).
Maps to save, forcing the method to be upsert
.
Datastore key object(s).
Static
doubleStatic
geoHelper function to get a Datastore Geo Point object.
Coordinate value.
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));
Static
intHelper function to get a Datastore Integer object.
This is also useful when using an ID outside the bounds of a JavaScript Number object.
The integer value.
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')
]);
Static
isHelper function to check if something is a Datastore Double object.
Optional
value: {}const {Datastore} = require('@google-cloud/datastore');
const datastore = new Datastore();
datastore.isDouble(0.42); // false
datastore.isDouble(datastore.double(0.42)); // true
Static
isHelper function to check if something is a Datastore Geo Point object.
Optional
value: {}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
Static
isHelper function to check if something is a Datastore Integer object.
Optional
value: {}const {Datastore} = require('@google-cloud/datastore');
const datastore = new Datastore();
datastore.isInt(42); // false
datastore.isInt(datastore.int(42)); // true
Static
isHelper function to check if something is a Datastore Key object.
Optional
value: {}const {Datastore} = require('@google-cloud/datastore');
const datastore = new Datastore();
datastore.isKey({path: ['Company', 123]}); // false
datastore.isKey(datastore.key(['Company', 123])); // true
Static
prepareInternal
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) => {})
The user's input object.
Generated using TypeDoc
Idiomatic class for interacting with Cloud Datastore. Uses the lower-level DatastoreClient class under the hood.
In addition to the constructor options shown here, the Datastore class constructor accepts the same options accepted by DatastoreClient.
The Datastore Emulator
Make sure you have the gcloud SDK installed, then run:
You will see the following printed:
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 aprojectId
.See Cloud Datastore Concepts Overview
Param
Configuration options.
Param
Override the default API endpoint used to reach Datastore. This is useful for connecting to your local Datastore server (usually "http://localhost:8080").
Param
Namespace to isolate transactions to.
Example
Import the client library
Example
Create a client that uses Application Default Credentials (ADC):
Example
Create a client with explicit credentials:
Example
Retrieving Records
Example
Paginating Records
Example
Creating Records
Example
Deleting Records
Example
Transactions
Example
Queries with Ancestors