@google-cloud/datastore
- Version 11.0.1
- Published
- 423 kB
- 11 dependencies
- Apache-2.0 license
Install
npm i @google-cloud/datastoreyarn add @google-cloud/datastorepnpm add @google-cloud/datastoreOverview
Cloud Datastore Client Library for Node.js
Index
Functions
Classes
Datastore
- auth
- baseUrl_
- clients_
- createAggregationQuery()
- createQuery()
- customEndpoint_
- DatastoreRequest
- defaultBaseUrl_
- determineBaseUrl_()
- double()
- export()
- geoPoint()
- getDatabaseId()
- getIndexes()
- getIndexesStream()
- getProjectId()
- import()
- index()
- insert()
- int()
- isDouble()
- isGeoPoint()
- isInt()
- isKey()
- key()
- KEY
- KEY
- keyFromLegacyUrlsafe()
- keyToLegacyUrlSafe()
- MORE_RESULTS_AFTER_CURSOR
- MORE_RESULTS_AFTER_CURSOR
- MORE_RESULTS_AFTER_LIMIT
- MORE_RESULTS_AFTER_LIMIT
- namespace
- NO_MORE_RESULTS
- NO_MORE_RESULTS
- options
- port_
- Query
- save()
- transaction()
- Transaction
- update()
- upsert()
Interfaces
Type Aliases
Namespaces
Functions
function and
and: (filters: EntityFilter[]) => CompositeFilter;And filters are composed of many other filters and when they are applied then query results are only returned when they pass through all these other filters.
Parameter filters
The list of filters that make up the AND filter.
Returns
{CompositeFilter} A composite AND filter.
function or
or: (filters: EntityFilter[]) => CompositeFilter;Or filters are composed of many other filters and when they are applied then query results are returned when they pass through any of these other filters.
Parameter filters
The list of filters that make up the OR filter.
Returns
{CompositeFilter} A composite OR filter.
Classes
class AggregateField
abstract class AggregateField {}An AggregateField is a class that contains data that defines an aggregation.
property alias_
alias_?: string;method alias
alias: (alias?: string) => AggregateField;Sets the alias on the aggregate field that should be used.
Parameter alias
The label used in the results to describe this aggregate field when a query is run.
Returns
{AggregateField}
method average
static average: (property: string) => Average;Gets a copy of the Average aggregate field.
Parameter property
The property to use for the average calculation.
Returns
{Average}
method count
static count: () => Count;Gets a copy of the Count aggregate field.
Returns
{Count}
method sum
static sum: (property: string) => Sum;Gets a copy of the Sum aggregate field.
Parameter property
The property to use for the average calculation.
Returns
{Sum}
method toProto
abstract toProto: () => any;Gets the proto for the aggregate field.
class Datastore
class Datastore extends DatastoreRequest {}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:
$ 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_IDis recognized. If you have this set, you don't need to provide aprojectId.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 {@link Datastore#key} and// {@link 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.});//-// <h3>Querying Records</h3>//// Create a query with {@link Datastore#createQuery}.//-const query = datastore.createQuery('Company');//-// Multiple records can be found that match criteria with// {@link Query#filter}.//-query.filter('location', 'CA');//-// Records can also be ordered with {@link Query#order}.//-query.order('name');//-// The number of records returned can be specified with// {@link Query#limit}.//-query.limit(5);//-// Records' key structures can also be queried with// {@link Query#hasAncestor}.//-const ancestorKey = datastore.key(['ParentCompany', 'Alphabet']);query.hasAncestor(ancestorKey);//-// Run the query with {@link 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 {@link Datastore#save}.// The entity 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 {@link 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 {@link 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// {@link 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']); // childentity const cookieKey3 = datastore.key(['Customer', customerId2, 'Cookie','cookie93911']); // child entityconst 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);});
constructor
constructor(options?: DatastoreOptions);property auth
auth: GoogleAuth;property baseUrl_
baseUrl_?: string;property clients_
clients_: Map<string, ClientStub>;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;This is one of three values which may be returned from Datastore#runQuery, Transaction#runQuery, and Query#run as
info.moreResults.There *may* be more results after the specified end cursor.
{string}
property MORE_RESULTS_AFTER_CURSOR
MORE_RESULTS_AFTER_CURSOR: string;property MORE_RESULTS_AFTER_LIMIT
static MORE_RESULTS_AFTER_LIMIT: string;This is one of three values which may be returned from Datastore#runQuery, Transaction#runQuery, and Query#run as
info.moreResults.There *may* be more results after the specified 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;This is one of three values which may be returned from Datastore#runQuery, Transaction#runQuery, and Query#run as
info.moreResults.There are no more results left to query for.
{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 createAggregationQuery
createAggregationQuery: (query: Query) => AggregateQuery;Create an aggregation query from a Query.
Parameter query
A Query object.
method createQuery
createQuery: { (kind?: string): Query; (kind?: string[]): Query; (namespace: string, kind: string): Query; (namespace: string, kind: string[]): Query;};Create a query for the specified kind. See Query for all of the available methods.
Parameter namespace
Namespace.
Parameter kind
The kind to query.
Returns
{Query}
Example 1
const {Datastore} = require('@google-cloud/datastore');const datastore = new Datastore();const query = datastore.createQuery('Company');See Also
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);Helper function to get a Datastore Double object.
Parameter value
The double value.
Returns
{object}
method export
export: { (config: ExportEntitiesConfig): Promise<LongRunningResponse>; (config: ExportEntitiesConfig, callback: LongRunningCallback): void;};Export entities from this project to a Google Cloud Storage bucket.
Parameter config
Configuration object.
Parameter
{string | Bucket} config.bucket The
gs://bucketpath or a @google-cloud/storage Bucket object.Parameter
{string[]} [config.kinds] The kinds to include in this import.
Parameter
{string[]} [config.namespaces] The namespace IDs to include in this import.
Parameter
{object} [config.gaxOptions] Request configuration options, outlined here: https://googleapis.github.io/gax-nodejs/global.html#CallOptions.
Parameter callback
The callback function.
Parameter
{?error} callback.err An error returned while making this request.
Parameter
{Operation} callback.operation An operation object that can be used to check the status of the request.
method geoPoint
static geoPoint: (coordinates: entity.Coordinates) => entity.GeoPoint;Helper function to get a Datastore Geo Point object.
Parameter coordinates
The coordinates 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));Helper function to get a Datastore Geo Point object.
Parameter coordinates
The coordinates value.
Parameter
{number} coordinates.latitude Latitudinal value.
Parameter
{number} coordinates.longitude Longitudinal value.
Returns
{object}
method getDatabaseId
getDatabaseId: () => string | undefined;Gets the database id that all requests will be run against.
Returns
{string} The database id that the current client is set to that requests will run against.
method getIndexes
getIndexes: { (options?: GetIndexesOptions): Promise<GetIndexesResponse>; (options: GetIndexesOptions, callback: GetIndexesCallback): void; (callback: GetIndexesCallback): void;};Get all of the indexes in this project.
Parameter optionsOrCallback
Parameter
{object} [options.gaxOptions] Request configuration options, outlined here: https://googleapis.github.io/gax-nodejs/global.html#CallOptions.
Parameter callback
The callback function.
Parameter
{?error} callback.error An error returned while making this request.
Parameter
{Index[]} callback.indexes All matching Index instances.
Parameter
{object} callback.apiResponse The full API response. {void | Promise}
method getIndexesStream
getIndexesStream: (options?: GetIndexesOptions) => NodeJS.ReadableStream;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;};Import entities into this project from a remote file.
Parameter config
Configuration object.
Parameter
{string | File} config.file The
gs://bucket/filepath or a @google-cloud/storage File object.Parameter
{string[]} [config.kinds] The kinds to include in this import.
Parameter
{string[]} [config.namespaces] The namespace IDs to include in this import.
Parameter
{object} [config.gaxOptions] Request configuration options, outlined here: https://googleapis.github.io/gax-nodejs/global.html#CallOptions.
Parameter callback
The callback function.
Parameter
{?error} callback.err An error returned while making this request.
Parameter
{Operation} callback.operation An operation object that can be used to check the status of the request.
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;};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.
Parameter callback
The callback function.
Parameter
{?error} callback.err An error returned while making this request
Parameter
{object} callback.apiResponse The full API response.
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')]);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}
method isDouble
static isDouble: (value?: {}) => value is entity.Double;Helper function to check if something is a Datastore Double object.
Parameter value
The double value.
Returns
{boolean}
Example 1
const {Datastore} = require('@google-cloud/datastore');const datastore = new Datastore();datastore.isDouble(0.42); // falsedatastore.isDouble(datastore.double(0.42)); // trueHelper function to check if something is a Datastore Double object.
Parameter value
The double value.
Returns
{boolean}
method isGeoPoint
static isGeoPoint: (value?: {}) => value is entity.GeoPoint;Helper function to check if something is a Datastore Geo Point object.
Parameter value
The coordinates value.
Returns
{boolean}
Example 1
const {Datastore} = require('@google-cloud/datastore');const datastore = new Datastore();const coordinates = {latitude: 0,longitude: 0};datastore.isGeoPoint(coordinates); // falsedatastore.isGeoPoint(datastore.geoPoint(coordinates)); // trueHelper function to check if something is a Datastore Geo Point object.
Parameter value
The coordinates value.
Returns
{boolean}
method isInt
static isInt: (value?: {}) => value is entity.Int;Helper function to check if something is a Datastore Integer object.
Parameter value
The value to check
Returns
{boolean}
Example 1
const {Datastore} = require('@google-cloud/datastore');const datastore = new Datastore();datastore.isInt(42); // falsedatastore.isInt(datastore.int(42)); // trueHelper function to check if something is a Datastore Integer object.
Parameter value
The value to check
Returns
{boolean}
method isKey
static isKey: (value?: {}) => value is entity.Key;Helper function to check if something is a Datastore Key object.
Parameter value
Value to compare property to.
Returns
{boolean}
Example 1
const {Datastore} = require('@google-cloud/datastore');const datastore = new Datastore();datastore.isKey({path: ['Company', 123]}); // falsedatastore.isKey(datastore.key(['Company', 123])); // true
method key
key: { (options: entity.KeyOptions): entity.Key; (path: PathType[]): entity.Key; (path: string): entity.Key;};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.
Parameter options
Key path. To specify or override a namespace, you must use an object here to explicitly state it.
Parameter
{string|array} [options.path] Key path.
Parameter
{string} [options.namespace] Optional namespace.
Returns
{Key} A newly created Key from the options given.
Example 1
<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');Example 2
<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]);Example 3
<caption>If the ID integer is outside the bounds of a JavaScript Numberobject, create an Int.</caption>const {Datastore} = require('@google-cloud/datastore');const datastore = new Datastore();const key = datastore.key(['Company',datastore.int('100000000000001234')]);Example 4
<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']);Example 5
<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]});Example 6
<caption>Create a complete key that specifies an ancestor. This will create a Team entitywith 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']);Example 7
<caption>Create a incomplete key that specifies an ancestor. This will create an Employee entitywith 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']);
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;};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.
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.
Parameter callback
The callback function.
Parameter
{?error} callback.err An error returned while making this request
Parameter
{string} callback.urlSafeKey A Base64-encoded URL-safe key.
Example 1
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);});
method save
save: { (entities: Entities, gaxOptions?: CallOptions): Promise<SaveResponse>; (entities: any, gaxOptions: CallOptions, callback: CommitCallback): void; (entities: any, callback: CommitCallback): void;};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, orupdate) 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
excludeFromIndexesarray.To prevent large properties from being included in *all* indexes, you must supply
excludeLargeProperties: true. See below for an example.Transaction#save as save
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
Parameter
{boolean} [entities.excludeLargeProperties] Automatically exclude large properties from indexing. It help in storing large values.
Parameter
{string} [entities.method] Explicit method to use, either 'insert', 'update', or 'upsert'.
Parameter
{object} entities.data Data to save with the provided key. entity.
Parameter gaxOptions
Request configuration options, outlined here: https://googleapis.github.io/gax-nodejs/global.html#CallOptions.
Parameter callback
The callback function.
Parameter
{?error} callback.err An error returned while making this request
Parameter
{object} callback.apiResponse The full API response.
Throws
{Error} If an unrecognized method is provided.
Example 1
//-// 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];});
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;};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.
Parameter callback
The callback function.
Parameter
{?error} callback.err An error returned while making this request
Parameter
{object} callback.apiResponse The full API response.
method upsert
upsert: { (entities: Entities): Promise<UpsertResponse>; (entities: any, callback: CommitCallback): 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.
Parameter callback
The callback function.
Parameter
{?error} callback.err An error returned while making this request
Parameter
{object} callback.apiResponse The full API response.
class DatastoreRequest
class DatastoreRequest {}Handles request logic for Datastore API operations.
Creates requests to the Datastore endpoint. Designed to be inherited by the Datastore and Transaction classes.
property datastore
datastore: Datastore;property id
id: string | Uint8Array;property requestCallbacks_
requestCallbacks_: any;property requests_
requests_: any;property state
protected state: TransactionState;method allocateIds
allocateIds: { ( key: entity.Key, options: AllocateIdsOptions | number ): Promise<AllocateIdsResponse>; ( key: entity.Key, options: number | AllocateIdsOptions, callback: AllocateIdsCallback ): void;};Generate IDs without creating entities.
Parameter key
The key object to complete.
Parameter options
Either the number of IDs to allocate or an options object for further customization of the request.
Parameter
{number} options.allocations How many IDs to allocate.
Parameter
{object} [options.gaxOptions] Request configuration options, outlined here: https://googleapis.github.io/gax-nodejs/global.html#CallOptions.
Parameter callback
The callback function.
Parameter
{?error} callback.err An error returned while making this request
Parameter
{array} callback.keys The generated IDs
Parameter
{object} callback.apiResponse The full API response.
Example 1
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 providingan// incomplete key with a namespace. Similar to the previous example, thecall// below will create 100 new IDs, but from the Company kind that existsunder// 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];});
method checkExpired
protected checkExpired: () => void;method createReadStream
createReadStream: ( keys: Entities, options?: CreateReadStreamOptions) => Transform;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.
Throws
{Error} If read time and read consistency cannot both be specified.
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?: CallOptions): Promise<DeleteResponse>; (keys: any, callback: CommitCallback): void; (keys: any, gaxOptions: CallOptions, callback: CommitCallback): void;};Delete all entities identified with the specified key(s).
Parameter key
Datastore key object(s).
Parameter gaxOptions
Request configuration options, outlined here: https://googleapis.github.io/gax-nodejs/global.html#CallOptions.
Parameter callback
The callback function.
Parameter
{?error} callback.err An error returned while making this request
Parameter
{object} callback.apiResponse The full API response.
Example 1
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];});
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;};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
Datastore key object(s).
Parameter options
Optional configuration.
Parameter
{string} [options.consistency] Specify either
strongoreventual. If not specified, default values are chosen by Datastore for the operation. Learn more about strong and eventual consistency [here](https://cloud.google.com/datastore/docs/articles/balancing-strong-and-eventual-consistency-with-google-cloud-datastore).Parameter
{object} [options.gaxOptions] Request configuration options, outlined here: https://googleapis.github.io/gax-nodejs/global.html#CallOptions.
Parameter
{boolean | IntegerTypeCastOptions} [options.wrapNumbers=false] Wrap values of integerValue type in Datastore#Int objects. If a
boolean, this will wrap values in Datastore#Int objects. If anobject, this will return a value returned bywrapNumbers.integerTypeCastFunction. Please see IntegerTypeCastOptions for options descriptions.Parameter callback
The callback function.
Parameter
{?error} callback.err An error returned while making this request
Parameter
{object|object[]} callback.entity The entity object(s) which match the provided keys.
Throws
{Error} If at least one Key object is not provided.
Example 1
//-// 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];});
method merge
merge: { (entities: Entities): Promise<CommitResponse>; (entities: any, callback: CommitCallback): void;};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
excludeFromIndexesarray.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 merge to the same for provided key.
Parameter callback
The callback function.
Parameter
{?error} callback.err An error returned while making this request
Parameter
{object} callback.apiResponse The full API response.
method parseTransactionResponse
protected parseTransactionResponse: (resp?: { transaction?: Uint8Array | string | undefined | null;}) => void;This function saves results from a successful beginTransaction call.
Parameter response
The response from a call to begin a transaction that completed successfully.
method prepareGaxRequest_
prepareGaxRequest_: (config: RequestConfig, callback: Function) => void;Builds a request and sends it to the Gapic Layer.
Parameter config
Configuration object.
Parameter callback
The callback function.
method request_
request_: (config: RequestConfig, callback: RequestCallback) => void;Make a request to the API endpoint. Properties to indicate a transactional or non-transactional operation are added automatically.
Parameter config
Configuration object.
Parameter
{object} config.gaxOpts GAX options.
Parameter
{string} config.client The name of the gax client.
Parameter
{function} config.method The gax method to call.
Parameter
{object} config.reqOpts Request options.
Parameter callback
The callback function.
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 runAggregationQuery
runAggregationQuery: { ( query: AggregateQuery, options?: RunQueryOptions ): Promise<RunQueryResponse>; ( query: AggregateQuery, options: RunQueryOptions, callback: RunAggregationQueryCallback ): void; (query: AggregateQuery, callback: RunAggregationQueryCallback): void;};Datastore allows you to run aggregate queries by supplying aggregate fields which will determine the type of aggregation that is performed.
The query is run, and the results are returned in the second argument of the callback provided.
Parameter query
AggregateQuery object.
Parameter options
Optional configuration
Parameter callback
The callback function. If omitted, a promise is returned.
Throws
{Error} If read time and read consistency cannot both be specified.
method runQuery
runQuery: { (query: Query, options?: RunQueryOptions): Promise<RunQueryResponse>; (query: Query, options: RunQueryOptions, callback: RunQueryCallback): void; (query: Query, callback: RunQueryCallback): void;};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
A Query object
Parameter options
Optional configuration.
Parameter
{string} [options.consistency] Specify either
strongoreventual. If not specified, default values are chosen by Datastore for the operation. Learn more about strong and eventual consistency [here](https://cloud.google.com/datastore/docs/articles/balancing-strong-and-eventual-consistency-with-google-cloud-datastore).Parameter
{object} [options.gaxOptions] Request configuration options, outlined here: https://googleapis.github.io/gax-nodejs/global.html#CallOptions.
Parameter
{boolean | IntegerTypeCastOptions} [options.wrapNumbers=false] Wrap values of integerValue type in Datastore#Int objects. If a
boolean, this will wrap values in Datastore#Int objects. If anobject, this will return a value returned bywrapNumbers.integerTypeCastFunction. Please see IntegerTypeCastOptions for options descriptions.Parameter callback
The callback function. If omitted, a readable stream instance is returned.
Parameter
{?error} callback.err An error returned while making this request
Parameter
{object[]} callback.entities A list of entities.
Parameter
{object} callback.info An object useful for pagination.
Parameter
{?string} callback.info.endCursor Use this in a follow-up query to begin from where these results ended.
Parameter
{string} callback.info.moreResults 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 1
//-// Where you see `transaction`, assume this is the context that's relevantto// 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 insteadof// 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];});
method runQueryStream
runQueryStream: (query: Query, options?: RunQueryStreamOptions) => Transform;Get a list of entities as a readable object stream.
See Datastore#runQuery for a list of all available options.
Parameter query
A Query object
Parameter options
Optional configuration.
Parameter
{object} [options.gaxOptions] Request configuration options, outlined here: https://googleapis.github.io/gax-nodejs/global.html#CallOptions.
Throws
{Error} If read time and read consistency cannot both be specified.
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?: CallOptions): Promise<GetIndexResponse>; (callback: GetIndexCallback): void; (gaxOptions: CallOptions, callback: GetIndexCallback): void;};Get an index if it exists.
Parameter gaxOptions
Request configuration options, outlined here: https://googleapis.github.io/gax-nodejs/CallSettings.html.
Parameter callback
The callback function.
Parameter
{?error} callback.err An error returned while making this request.
Parameter
{Index} callback.index The Index instance.
Parameter
{object} callback.apiResponse The full API response.
method getMetadata
getMetadata: { (gaxOptions?: CallOptions): Promise<IndexGetMetadataResponse>; (callback: IndexGetMetadataCallback): void; (gaxOptions: CallOptions, callback: IndexGetMetadataCallback): void;};Get the metadata of this index.
Parameter gaxOptions
Request configuration options, outlined here: https://googleapis.github.io/gax-nodejs/CallSettings.html.
Parameter callback
The callback function.
Parameter
{?error} callback.err An error returned while making this request.
Parameter
{object} callback.metadata The metadata.
class PropertyFilter
class PropertyFilter<T extends string> extends EntityFilter implements IFilter {}A PropertyFilter is a filter that gets applied to a query directly.
See Also
constructor
constructor(name: string, op: Operator, val: {});Build a Property Filter object.
Parameter Property
The property name that the filter will be applied to.
Parameter operator
The comparison operator that the filter applies.
Parameter val
The value that the filter compares the property to.
property name
name: string;property op
op: Operator;property val
val: {};method toProto
toProto: () => any;Gets the proto for the filter.
class Query
class Query {}A Query object is used to build and execute queries for entities stored in Datastore.
Create a Query object with Datastore#createQuery or 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 entityFilters
entityFilters: EntityFilter[];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: { (filter: EntityFilter): Query; <T extends string>(property: T, value: AllowedFilterValueType<T>): Query; <T extends string>( property: T, operator: Operator, value: AllowedFilterValueType<T> ): Query;};Datastore allows querying on properties. Supported comparison operators are
=,<,>,<=,>=,!=,HAS_ANCESTOR,INandNOT_IN.*To filter by ancestors, see {module:datastore/query#hasAncestor}.*
Parameter propertyOrFilter
The field name.
Parameter operator
Operator (=, <, >, <=, >=).
Parameter value
Value to compare property to.
Returns
{Query}
Example 1
const {Datastore} = require('@google-cloud/datastore');const datastore = new Datastore();const query = datastore.createQuery('Company');//-// List all companies that are located in California.//-const caliQuery = query.filter('state', 'CA');//-// List all companies named Google that have less than 400 employees.//-const companyQuery = query.filter('name', 'Google').filter('size', '<', 400);//-// To filter by key, use `__key__` for the property name. Filter on keys// stored as properties is not currently supported.//-const key = datastore.key(['Company', 'Google']);const keyQuery = query.filter('__key__', key);See Also
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: Key) => this;Filter a query by ancestors.
Parameter key
Key object to filter by.
Returns
{Query}
Example 1
const {Datastore} = require('@google-cloud/datastore');const datastore = new Datastore();const query = datastore.createQuery('MyKind');const ancestoryQuery = query.hasAncestor(datastore.key(['Parent', 123]));See Also
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;};Run the query.
Parameter options
Optional configuration.
Parameter
{string} [options.consistency] Specify either
strongoreventual. If not specified, default values are chosen by Datastore for the operation. Learn more about strong and eventual consistency [here](https://cloud.google.com/datastore/docs/articles/balancing-strong-and-eventual-consistency-with-google-cloud-datastore).Parameter
{object} [options.gaxOptions] Request configuration options, outlined here: https://googleapis.github.io/gax-nodejs/global.html#CallOptions.
Parameter
{boolean | IntegerTypeCastOptions} [options.wrapNumbers=false] Wrap values of integerValue type in Datastore#Int objects. If a
boolean, this will wrap values in Datastore#Int objects. If anobject, this will return a value returned bywrapNumbers.integerTypeCastFunction. Please see IntegerTypeCastOptions for options descriptions.Parameter callback
The callback function. If omitted, a readable stream instance is returned.
Parameter
{?error} callback.err An error returned while making this request
Parameter
{object[]} callback.entities A list of entities.
Parameter
{object} callback.info An object useful for pagination.
Parameter
{?string} callback.info.endCursor Use this in a follow-up query to begin from where these results ended.
Parameter
{string} callback.info.moreResults 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 1
const {Datastore} = require('@google-cloud/datastore');const datastore = new Datastore();const query = datastore.createQuery('Company');query.run((err, entities, info) => {// entities = An array of records.// Access the Key object for an entity.const firstEntityKey = entities[0][datastore.KEY];});//-// A keys-only query returns just the keys of the result entities insteadof// the entities themselves, at lower latency and cost.//-query.select('__key__');query.run((err, entities) => {const keys = entities.map((entity) => {return entity[datastore.KEY];});});//-// If the callback is omitted, we'll return a Promise.//-query.run().then((data) => {const entities = data[0];});
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
{Request}
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?: CallOptions): Promise<CommitResponse>; (callback: CommitCallback): void; (gaxOptions: CallOptions, callback: CommitCallback): void;};Commit the remote transaction and finalize the current transaction instance.
If the commit request fails, we will automatically rollback the transaction.
Parameter gaxOptions
Request configuration options.
Parameter callback
The callback function.
Parameter
{?error} callback.err An error returned while making this request. If the commit fails, we automatically try to rollback the transaction (see {module:datastore/transaction#rollback}).
Parameter
{object} callback.apiResponse The full API response.
Example 1
const {Datastore} = require('@google-cloud/datastore');const datastore = new Datastore();const transaction = datastore.transaction();transaction.commit((err, apiResponse) => {if (err) {// Transaction could not be committed.}});//-// If the callback is omitted, we'll return a Promise.//-transaction.commit().then((data) => {const apiResponse = data[0];});Parameter gaxOptions
Request configuration options, outlined here: https://googleapis.github.io/gax-nodejs/global.html#CallOptions.
Parameter callback
The callback function.
Parameter
{?error} callback.err An error returned while making this request. If the commit fails, we automatically try to rollback the transaction (see {module:datastore/transaction#rollback}).
Parameter
{object} callback.apiResponse The full API response.
method createAggregationQuery
createAggregationQuery: (query: Query) => AggregateQuery;Create an aggregation query from the query specified. See {module:datastore/query} for all of the available methods.
Parameter query
A Query object
method createQuery
createQuery: { (kind?: string): Query; (kind?: string[]): Query; (namespace: string, kind: string): Query; (namespace: string, kind: string[]): Query;};Create a query for the specified kind. See {module:datastore/query} for all of the available methods.
Parameter namespace
Namespace.
Parameter kind
The kind to query.
Returns
{Query}
Example 1
const {Datastore} = require('@google-cloud/datastore');const datastore = new Datastore();const transaction = datastore.transaction();// Run the query inside the transaction.transaction.run((err) => {if (err) {// Error handling omitted.}const ancestorKey = datastore.key(['ParentCompany', 'Alphabet']);const query = transaction.createQuery('Company').hasAncestor(ancestorKey);query.run((err, entities) => {if (err) {// Error handling omitted.}transaction.commit((err) => {if (!err) {// Transaction committed successfully.}});});});// Run the query inside the transaction.with namespacetransaction.run((err) => {if (err) {// Error handling omitted.}const ancestorKey = datastore.key(['ParentCompany', 'Alphabet']);const query = transaction.createQuery('CompanyNamespace', 'Company').hasAncestor(ancestorKey);query.run((err, entities) => {if (err) {// Error handling omitted.}transaction.commit((err) => {if (!err) {// Transaction committed successfully.}});});});See Also
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 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;};This function calls get on the super class. If the transaction has not been started yet then the transaction is started before the get call is made.
Parameter keys
Datastore key object(s).
Parameter options
Optional configuration.
Parameter callback
The callback function.
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?: CallOptions): Promise<RollbackResponse>; (gaxOptions: CallOptions, callback: RollbackCallback): void;};Reverse a transaction remotely and finalize the current transaction instance.
Parameter gaxOptions
Request configuration options, outlined here: https://googleapis.github.io/gax-nodejs/global.html#CallOptions.
Parameter callback
The callback function.
Parameter
{?error} callback.err An error returned while making this request.
Parameter
{object} callback.apiResponse The full API response.
Example 1
const {Datastore} = require('@google-cloud/datastore');const datastore = new Datastore();const transaction = datastore.transaction();transaction.run((err) => {if (err) {// Error handling omitted.}transaction.rollback((err) => {if (!err) {// Transaction rolled back successfully.}});});//-// If the callback is omitted, we'll return a Promise.//-transaction.rollback().then((data) => {const apiResponse = data[0];});
method run
run: { (options?: RunOptions): Promise<RunResponse>; (callback: RunCallback): void; (options: RunOptions, callback: RunCallback): void;};Begin a remote transaction. In the callback provided, run your transactional commands.
Parameter options
Configuration object.
Parameter
{object} [options.gaxOptions] Request configuration options, outlined here: https://googleapis.github.io/gax-nodejs/global.html#CallOptions.
Parameter
{boolean} [options.readOnly=false] A read-only transaction cannot modify entities.
Parameter
{string} [options.transactionId] The ID of a previous transaction.
Parameter callback
The function to execute within the context of a transaction.
Parameter
{?error} callback.err An error returned while making this request.
Parameter
{Transaction} callback.transaction This transaction instance.
Parameter
{object} callback.apiResponse The full API response.
Example 1
const {Datastore} = require('@google-cloud/datastore');const datastore = new Datastore();const transaction = datastore.transaction();transaction.run((err, transaction) => {// Perform Datastore transactional operations.const key = datastore.key(['Company', 123]);transaction.get(key, (err, entity) => {entity.name = 'Google';transaction.save({key: key,data: entity});transaction.commit((err) => {if (!err) {// Data saved successfully.}});});});//-// If the callback is omitted, we'll return a Promise.//-transaction.run().then((data) => {const transaction = data[0];const apiResponse = data[1];});
method runAggregationQuery
runAggregationQuery: { ( query: AggregateQuery, options?: RunQueryOptions ): Promise<RunQueryResponse>; ( query: AggregateQuery, options: RunQueryOptions, callback: RequestCallback ): void; (query: AggregateQuery, callback: RequestCallback): void;};This function calls runAggregationQuery on the super class. If the transaction has not been started yet then the transaction is started before the runAggregationQuery call is made.
Parameter query
AggregateQuery object.
Parameter options
Optional configuration
Parameter callback
The callback function. If omitted, a promise is returned.
method runQuery
runQuery: { (query: Query, options?: RunQueryOptions): Promise<RunQueryResponse>; (query: Query, options: RunQueryOptions, callback: RunQueryCallback): void; (query: Query, callback: RunQueryCallback): void;};This function calls runQuery on the super class. If the transaction has not been started yet then the transaction is started before the runQuery call is made.
Parameter query
A Query object
Parameter options
Optional configuration.
Parameter callback
The callback function. If omitted, a readable stream instance is returned.
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, orupdate) 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
excludeFromIndexesarray. 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
<caption>Save a single entity.</caption>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
<caption>Save multiple entities at once.</caption>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 databaseId
databaseId?: string;property fallback
fallback?: Fallback;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 {}Type Aliases
type Entity
type Entity = any & EntityWithTransforms;type Fallback
type Fallback = boolean | 'rest' | 'proto';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;Namespaces
namespace v1
module 'build/src/v1/index.d.ts' {}Package Files (9)
Dependencies (11)
Dev Dependencies (26)
Peer Dependencies (0)
No peer dependencies.
Badge
To add a badge like this oneto 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[](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>
- Updated .
Package analyzed in 4992 ms. - Missing or incorrect documentation? Open an issue for this package.
