Class Datastore (9.1.0)

Idiomatic class for interacting with Cloud Datastore. Uses the lower-levelDatastoreClient class under the hood.

In addition to the constructor options shown here, theDatastore class constructor accepts the same options accepted byDatastoreClient.

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

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

SeeCloud Datastore Concepts Overview

Inheritance

DatastoreRequest >Datastore

Package

@google-cloud/datastore

Examples

Import the client library

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

Create a client that usesApplication Default Credentials (ADC):

constdatastore=newDatastore();

Create a client withexplicit credentials:

constdatastore=newDatastore({projectId:'your-project-id',keyFilename:'/path/to/keyfile.json'});

Retrieving Records

const{Datastore}=require('@google-cloud/datastore');constdatastore=newDatastore();// 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}.//-constkey=datastore.key(['Company','Google']);datastore.get(key,function(err,entity){// entity = The record.// entity[datastore.KEY] = The key for this entity.});//-//

Querying Records

//// Create a query with {@link Datastore#createQuery}.//-constquery=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}.//-constancestorKey=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.constfirstEntityKey=entities[0][datastore.KEY];});

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.//-constexpress=require('express');constapp=express();constNUM_RESULTS_PER_PAGE=15;app.get('/contacts',(req,res)=>{constquery=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.constfrontEndResponse={contacts:entities};// Check if  more results may exist.if(info.moreResults!==datastore.NO_MORE_RESULTS){frontEndResponse.nextPageCursor=info.endCursor;}res.render('contacts',frontEndResponse);});});

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".//-constkey=datastore.key(['Company','Google']);constdata={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.}});

Deleting Records

// Entities can be removed from Datastore by passing the entity's key object// to {@link Datastore#delete}.//-constkey=datastore.key(['Company','Google']);datastore.delete(key,(err)=>{if(!err){// Record deleted successfully.}});

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.//-consttransaction=datastore.transaction();transaction.run((err)=>{if(err){// Error handling omitted.}constkey=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.}});});});

Queries with Ancestors

const{Datastore}=require('@google-cloud/datastore');constdatastore=newDatastore();constcustomerId1=2993844;constcustomerId2=4993882;constcustomerKey1=datastore.key(['Customer',customerId1]);constcustomerKey2=datastore.key(['Customer',customerId2]);constcookieKey1=datastore.key(['Customer',customerId1,'Cookie','cookie28839']);// child entity const cookieKey2 =datastore.key(['Customer',customerId1,'Cookie','cookie78984']);// childentityconstcookieKey3=datastore.key(['Customer',customerId2,'Cookie','cookie93911']);// child entityconstentities=[];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);constquery=datastore.createQuery().hasAncestor(customerKey1);datastore.runQuery(query,(err,entities)=>{for(letentityofentities){console.log(entity[datastore.KEY]);}});constquery2=datastore.createQuery().hasAncestor(customerKey2);datastore.runQuery(query2,(err,entities)=>{for(letentityofentities){console.log(entity[datastore.KEY]);}});datastore.runQuery(query2,(entities)=>{console.log(entities);});

Constructors

(constructor)(options)

constructor(options?:DatastoreOptions);

Constructs a new instance of theDatastore class

Parameter
NameDescription
optionsDatastoreOptions

Properties

auth

auth:GoogleAuth;

baseUrl_

baseUrl_?:string;

clients_

clients_:Map<string,ClientStub>;

customEndpoint_

customEndpoint_?:boolean;

DatastoreRequest

DatastoreRequest:typeofDatastoreRequest;

DatastoreRequest class.

Datastore.DatastoreRequest

defaultBaseUrl_

defaultBaseUrl_:string;

KEY

KEY:typeofentity.KEY_SYMBOL;

KEY

staticKEY:typeofentity.KEY_SYMBOL;

Access the Key from an Entity object.

Datastore#KEY {symbol}

MORE_RESULTS_AFTER_CURSOR

MORE_RESULTS_AFTER_CURSOR:string;

MORE_RESULTS_AFTER_CURSOR

staticMORE_RESULTS_AFTER_CURSOR:string;

This is one of three values which may be returned from , , and asinfo.moreResults.

There *may* be more results after the specified end cursor.

{string}

MORE_RESULTS_AFTER_LIMIT

MORE_RESULTS_AFTER_LIMIT:string;

MORE_RESULTS_AFTER_LIMIT

staticMORE_RESULTS_AFTER_LIMIT:string;

This is one of three values which may be returned from , , and asinfo.moreResults.

There *may* be more results after the specified limit.

{string}

namespace

namespace?:string;

NO_MORE_RESULTS

NO_MORE_RESULTS:string;

NO_MORE_RESULTS

staticNO_MORE_RESULTS:string;

This is one of three values which may be returned from , , and asinfo.moreResults.

There are no more results left to query for.

{string}

options

options:DatastoreOptions;

port_

port_?:number;

Query

Query:typeofQuery;

Query class.

Datastore.Query

Transaction

Transaction:typeofTransaction;

Transaction class.

Datastore.Transaction

Methods

createAggregationQuery(query)

createAggregationQuery(query:Query):AggregateQuery;

Create an aggregation query from a Query.

Parameter
NameDescription
queryQuery

A Query object.

Returns
TypeDescription
AggregateQuery

createQuery(kind)

createQuery(kind?:string):Query;

Create a query for the specified kind. SeeQuery for all of the available methods.

Parameter
NameDescription
kindstring

The kind to query.

Returns
TypeDescription
Query

{Query}

Example
const{Datastore}=require('@google-cloud/datastore');constdatastore=newDatastore();constquery=datastore.createQuery('Company');

createQuery(kind)

createQuery(kind?:string[]):Query;
Parameter
NameDescription
kindstring[]
Returns
TypeDescription
Query

createQuery(namespace, kind)

createQuery(namespace:string,kind:string):Query;
Parameters
NameDescription
namespacestring
kindstring
Returns
TypeDescription
Query

createQuery(namespace, kind)

createQuery(namespace:string,kind:string[]):Query;
Parameters
NameDescription
namespacestring
kindstring[]
Returns
TypeDescription
Query

determineBaseUrl_(customApiEndpoint)

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
NameDescription
customApiEndpointstring

Custom API endpoint.

Returns
TypeDescription
void

double(value)

double(value:number):entity.Double;
Parameter
NameDescription
valuenumber
Returns
TypeDescription
entity.Double

double(value)

staticdouble(value:number):entity.Double;

Helper function to get a Datastore Double object.

Parameter
NameDescription
valuenumber

The double value.

Returns
TypeDescription
entity.Double

{object}

Example
const{Datastore}=require('@google-cloud/datastore');constdatastore=newDatastore();constthreeDouble=datastore.double(3.0);

export(config)

export(config:ExportEntitiesConfig):Promise<LongRunningResponse>;

Export entities from this project to a Google Cloud Storage bucket.

Parameter
NameDescription
configExportEntitiesConfig

Configuration object.

Returns
TypeDescription
Promise<LongRunningResponse>

export(config, callback)

export(config:ExportEntitiesConfig,callback:LongRunningCallback):void;
Parameters
NameDescription
configExportEntitiesConfig
callbackLongRunningCallback
Returns
TypeDescription
void

geoPoint(coordinates)

geoPoint(coordinates:entity.Coordinates):entity.GeoPoint;
Parameter
NameDescription
coordinatesentity.Coordinates
Returns
TypeDescription
entity.GeoPoint

geoPoint(coordinates)

staticgeoPoint(coordinates:entity.Coordinates):entity.GeoPoint;

Helper function to get a Datastore Geo Point object.

Parameter
NameDescription
coordinatesentity.Coordinates

Coordinate value.

Returns
TypeDescription
entity.GeoPoint

{object}

Example
const{Datastore}=require('@google-cloud/datastore');constdatastore=newDatastore();constcoordinates={latitude:40.6894,longitude:-74.0447};constgeoPoint=datastore.geoPoint(coordinates);//-// List all companies that are located at 40.123 latitude// and -74.0447 longitude.//-constquery=datastore.createQuery('Company');constcompanyQuery=query.filter('geoPoint.latitude',datastore.double(40.123)).filter('geoPoint.longitude',datastore.double(-74.0447));

getDatabaseId()

getDatabaseId():string|undefined;

Gets the database id that all requests will be run against.

Returns
TypeDescription
string | undefined

{string} The database id that the current client is set to that requests will run against.

getIndexes(options)

getIndexes(options?:GetIndexesOptions):Promise<GetIndexesResponse>;

Get all of the indexes in this project.

Parameter
NameDescription
optionsGetIndexesOptions
Returns
TypeDescription
Promise<GetIndexesResponse>

getIndexes(options, callback)

getIndexes(options:GetIndexesOptions,callback:GetIndexesCallback):void;
Parameters
NameDescription
optionsGetIndexesOptions
callbackGetIndexesCallback
Returns
TypeDescription
void

getIndexes(callback)

getIndexes(callback:GetIndexesCallback):void;
Parameter
NameDescription
callbackGetIndexesCallback
Returns
TypeDescription
void

getIndexesStream(options)

getIndexesStream(options?:GetIndexesOptions):NodeJS.ReadableStream;

Get all of the indexes in this project as a readable object stream.

Parameter
NameDescription
optionsGetIndexesOptions

Configuration object. See for a complete list of options.

Returns
TypeDescription
NodeJS.ReadableStream

{ReadableStream

getProjectId()

getProjectId():Promise<string>;
Returns
TypeDescription
Promise<string>

import(config)

import(config:ImportEntitiesConfig):Promise<LongRunningResponse>;

Import entities into this project from a remote file.

Parameter
NameDescription
configImportEntitiesConfig

Configuration object.

Returns
TypeDescription
Promise<LongRunningResponse>

import(config, callback)

import(config:ImportEntitiesConfig,callback:LongRunningCallback):void;
Parameters
NameDescription
configImportEntitiesConfig
callbackLongRunningCallback
Returns
TypeDescription
void

index(id)

index(id:string):Index;

Get a reference to an Index.

Parameter
NameDescription
idstring

The index name or id.

Returns
TypeDescription
Index

{Index}

insert(entities)

insert(entities:Entities):Promise<InsertResponse>;

Maps toDatastore#save, forcing the method to beinsert.

Parameter
NameDescription
entitiesEntities

Datastore key object(s).

Returns
TypeDescription
Promise<InsertResponse>

insert(entities, callback)

insert(entities:Entities,callback:InsertCallback):void;
Parameters
NameDescription
entitiesEntities
callbackInsertCallback
Returns
TypeDescription
void

int(value)

int(value:number|string):entity.Int;
Parameter
NameDescription
valuenumber | string
Returns
TypeDescription
entity.Int

int(value)

staticint(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
NameDescription
valuenumber | string

The integer value.

Returns
TypeDescription
entity.Int

{object}

Example
const{Datastore}=require('@google-cloud/datastore');constdatastore=newDatastore();constsevenInteger=datastore.int(7);//-// Create an Int to support long Key IDs.//-constkey=datastore.key(['Kind',datastore.int('100000000000001234')]);

isDouble(value)

isDouble(value?:{}):valueisentity.Double;
Parameter
NameDescription
value{}
Returns
TypeDescription
value isentity.Double

isDouble(value)

staticisDouble(value?:{}):valueisentity.Double;

Helper function to check if something is a Datastore Double object.

Parameter
NameDescription
value{}
Returns
TypeDescription
value isentity.Double

{boolean}

Example
const{Datastore}=require('@google-cloud/datastore');constdatastore=newDatastore();datastore.isDouble(0.42);// falsedatastore.isDouble(datastore.double(0.42));// true

isGeoPoint(value)

isGeoPoint(value?:{}):valueisentity.GeoPoint;
Parameter
NameDescription
value{}
Returns
TypeDescription
value isentity.GeoPoint

isGeoPoint(value)

staticisGeoPoint(value?:{}):valueisentity.GeoPoint;

Helper function to check if something is a Datastore Geo Point object.

Parameter
NameDescription
value{}
Returns
TypeDescription
value isentity.GeoPoint

{boolean}

Example
const{Datastore}=require('@google-cloud/datastore');constdatastore=newDatastore();constcoordinates={latitude:0,longitude:0};datastore.isGeoPoint(coordinates);// falsedatastore.isGeoPoint(datastore.geoPoint(coordinates));// true

isInt(value)

isInt(value?:{}):valueisentity.Int;
Parameter
NameDescription
value{}
Returns
TypeDescription
value isentity.Int

isInt(value)

staticisInt(value?:{}):valueisentity.Int;

Helper function to check if something is a Datastore Integer object.

Parameter
NameDescription
value{}
Returns
TypeDescription
value isentity.Int

{boolean}

Example
const{Datastore}=require('@google-cloud/datastore');constdatastore=newDatastore();datastore.isInt(42);// falsedatastore.isInt(datastore.int(42));// true

isKey(value)

isKey(value?:{}):valueisentity.Key;
Parameter
NameDescription
value{}
Returns
TypeDescription
value isentity.Key

isKey(value)

staticisKey(value?:{}):valueisentity.Key;

Helper function to check if something is a Datastore Key object.

Parameter
NameDescription
value{}
Returns
TypeDescription
value isentity.Key

{boolean}

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

key(options)

key(options:entity.KeyOptions):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
NameDescription
optionsentity.KeyOptions

Key path. To specify or override a namespace, you must use an object here to explicitly state it.

Returns
TypeDescription
Key

{Key} A newly created Key from the options given.

Examples
Createanincompletekeywithakindvalueof`Company`.SincenoIdissupplied,Datastorewillgenerateoneonsave.const{Datastore}=require('@google-cloud/datastore');constdatastore=newDatastore();constkey=datastore.key('Company');
Createacompletekeywithakindvalueof`Company`andId`123`.const{Datastore}=require('@google-cloud/datastore');constdatastore=newDatastore();constkey=datastore.key(['Company',123]);
IftheIDintegerisoutsidetheboundsofaJavaScriptNumberobject,createanInt.const{Datastore}=require('@google-cloud/datastore');constdatastore=newDatastore();constkey=datastore.key(['Company',datastore.int('100000000000001234')]);
Createacompletekeywithakindvalueof`Company`andname`Google`.BecausethesuppliedIdisastring,Datastorewillprefixitwith"name=".HadthesuppliedIdbeennumeric,Datastorewouldprefixitwiththestandard,"id=".const{Datastore}=require('@google-cloud/datastore');constdatastore=newDatastore();constkey=datastore.key(['Company','Google']);
Createacompletekeyfromaprovidednamespaceandpath.const{Datastore}=require('@google-cloud/datastore');constdatastore=newDatastore();constkey=datastore.key({namespace:'My-NS',path:['Company',123]});
Createacompletekeythatspecifiesanancestor.ThiswillcreateaTeamentitywithanameof"Datastore",whichbelongstotheCompanywiththe"name=Google"key.const{Datastore}=require('@google-cloud/datastore');constdatastore=newDatastore();constkey=datastore.key(['Company','Google','Team','Datastore']);
Createaincompletekeythatspecifiesanancestor.ThiswillcreateanEmployeeentitywithanauto-generatedId,whichbelongstotheCompanywiththe"name=Google"key.const{Datastore}=require('@google-cloud/datastore');constdatastore=newDatastore();constkey=datastore.key(['Company','Google','Employee']);

key(path)

key(path:PathType[]):entity.Key;
Parameter
NameDescription
pathPathType[]
Returns
TypeDescription
Key

key(path)

key(path:string):entity.Key;
Parameter
NameDescription
pathstring
Returns
TypeDescription
Key

keyFromLegacyUrlsafe(key)

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
NameDescription
keystring

Entity key object.

Returns
TypeDescription
Key

{string} Created urlsafe key.

Example
const{Datastore}=require('@google-cloud/datastore');constdatastore=newDatastore();consturlSafeKey='ag9ncmFzcy1jbHVtcC00NzlyEwsSB0NvbXBhbnkiBkdvb2dsZQw';datastore.keyFromLegacyUrlsafe(key);

keyToLegacyUrlSafe(key, locationPrefix)

keyToLegacyUrlSafe(key:entity.Key,locationPrefix?:string):Promise<string>;

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.

Parameters
NameDescription
keyKey

Entity key object.

locationPrefixstring

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
TypeDescription
Promise<string>
Example
const{Datastore}=require('@google-cloud/datastore');constdatastore=newDatastore();constkey=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.//-constlocationPrefix='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)=>{consturlSafeKey=data[0];console.log(urlSafeKey);});

keyToLegacyUrlSafe(key, callback)

keyToLegacyUrlSafe(key:entity.Key,callback:KeyToLegacyUrlSafeCallback):void;
Parameters
NameDescription
keyKey
callbackKeyToLegacyUrlSafeCallback
Returns
TypeDescription
void

keyToLegacyUrlSafe(key, locationPrefix, callback)

keyToLegacyUrlSafe(key:entity.Key,locationPrefix:string,callback:KeyToLegacyUrlSafeCallback):void;
Parameters
NameDescription
keyKey
locationPrefixstring
callbackKeyToLegacyUrlSafeCallback
Returns
TypeDescription
void

save(entities, gaxOptions)

save(entities:Entities,gaxOptions?:CallOptions):Promise<SaveResponse>;

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 anexcludeFromIndexes array.

To prevent large properties from being included in *all* indexes, you must supplyexcludeLargeProperties: true. See below for an example.

as save

Parameters
NameDescription
entitiesEntities

Datastore key object(s).

gaxOptionsCallOptions

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

Returns
TypeDescription
Promise<SaveResponse>
Example
//-// Save a single entity.//// Notice that we are providing an incomplete key. After saving, the// original Key object used to save will be updated to contain the path// with its generated ID.//-constkey=datastore.key('Company');constentity={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.//-constkey=datastore.key(['Company','donutshack']);constentity={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.//-constkey=datastore.key({namespace:'my-namespace',path:['Company','donutshack']});constentity={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.//-constkey=datastore.key('Company');constentity={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:newDate('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.//-constentity={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.//-constentity={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.//-constcompanyKey=datastore.key(['Company',123]);constproductKey=datastore.key(['Product','Computer']);constentities=[{key:companyKey,data:{HQ:'Dallas, TX'}},{key:productKey,data:{vendor:'Dell'}}];datastore.save(entities,(err,apiResponse)=>{});//-// Explicitly attempt to 'insert' a specific entity.//-constuserKey=datastore.key(['User','chilts']);constentity={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)=>{constapiResponse=data[0];});

save(entities, gaxOptions, callback)

save(entities:Entities,gaxOptions:CallOptions,callback:SaveCallback):void;
Parameters
NameDescription
entitiesEntities
gaxOptionsCallOptions
callbackSaveCallback
Returns
TypeDescription
void

save(entities, callback)

save(entities:Entities,callback:SaveCallback):void;
Parameters
NameDescription
entitiesEntities
callbackSaveCallback
Returns
TypeDescription
void

transaction(options)

transaction(options?:TransactionOptions):Transaction;

Create a new Transaction object.

Parameter
NameDescription
optionsTransactionOptions

Configuration object.

Returns
TypeDescription
Transaction

{Transaction}

Example
const{Datastore}=require('@google-cloud/datastore');constdatastore=newDatastore();consttransaction=datastore.transaction();

update(entities)

update(entities:Entities):Promise<UpdateResponse>;

Maps toDatastore#save, forcing the method to beupdate.

Parameter
NameDescription
entitiesEntities

Datastore key object(s).

Returns
TypeDescription
Promise<UpdateResponse>

update(entities, callback)

update(entities:Entities,callback:UpdateCallback):void;
Parameters
NameDescription
entitiesEntities
callbackUpdateCallback
Returns
TypeDescription
void

upsert(entities)

upsert(entities:Entities):Promise<UpsertResponse>;

Maps toDatastore#save, forcing the method to beupsert.

Parameter
NameDescription
entitiesEntities

Datastore key object(s).

Returns
TypeDescription
Promise<UpsertResponse>

upsert(entities, callback)

upsert(entities:Entities,callback:UpsertCallback):void;
Parameters
NameDescription
entitiesEntities
callbackUpsertCallback
Returns
TypeDescription
void

Except as otherwise noted, the content of this page is licensed under theCreative Commons Attribution 4.0 License, and code samples are licensed under theApache 2.0 License. For details, see theGoogle Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.

Last updated 2025-10-30 UTC.