Class Datastore (9.1.0) Stay organized with collections Save and categorize content based on your preferences.
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.
Package
@google-cloud/datastoreExamples
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 | |
|---|---|
| Name | Description |
options | DatastoreOptions |
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 | |
|---|---|
| Name | Description |
query | QueryA Query object. |
| Returns | |
|---|---|
| Type | Description |
AggregateQuery | |
createQuery(kind)
createQuery(kind?:string):Query;Create a query for the specified kind. SeeQuery for all of the available methods.
| Parameter | |
|---|---|
| Name | Description |
kind | stringThe kind to query. |
| Returns | |
|---|---|
| Type | Description |
Query | {Query} |
const{Datastore}=require('@google-cloud/datastore');constdatastore=newDatastore();constquery=datastore.createQuery('Company');createQuery(kind)
createQuery(kind?:string[]):Query;| Parameter | |
|---|---|
| Name | Description |
kind | string[] |
| Returns | |
|---|---|
| Type | Description |
Query | |
createQuery(namespace, kind)
createQuery(namespace:string,kind:string):Query;| Parameters | |
|---|---|
| Name | Description |
namespace | string |
kind | string |
| Returns | |
|---|---|
| Type | Description |
Query | |
createQuery(namespace, kind)
createQuery(namespace:string,kind:string[]):Query;| Parameters | |
|---|---|
| Name | Description |
namespace | string |
kind | string[] |
| Returns | |
|---|---|
| Type | Description |
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 | |
|---|---|
| Name | Description |
customApiEndpoint | stringCustom API endpoint. |
| Returns | |
|---|---|
| Type | Description |
void | |
double(value)
double(value:number):entity.Double;| Parameter | |
|---|---|
| Name | Description |
value | number |
| Returns | |
|---|---|
| Type | Description |
entity.Double | |
double(value)
staticdouble(value:number):entity.Double;Helper function to get a Datastore Double object.
| Parameter | |
|---|---|
| Name | Description |
value | numberThe double value. |
| Returns | |
|---|---|
| Type | Description |
entity.Double | {object} |
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 | |
|---|---|
| Name | Description |
config | ExportEntitiesConfigConfiguration object. |
| Returns | |
|---|---|
| Type | Description |
Promise<LongRunningResponse> | |
export(config, callback)
export(config:ExportEntitiesConfig,callback:LongRunningCallback):void;| Parameters | |
|---|---|
| Name | Description |
config | ExportEntitiesConfig |
callback | LongRunningCallback |
| Returns | |
|---|---|
| Type | Description |
void | |
geoPoint(coordinates)
geoPoint(coordinates:entity.Coordinates):entity.GeoPoint;| Parameter | |
|---|---|
| Name | Description |
coordinates | entity.Coordinates |
| Returns | |
|---|---|
| Type | Description |
entity.GeoPoint | |
geoPoint(coordinates)
staticgeoPoint(coordinates:entity.Coordinates):entity.GeoPoint;Helper function to get a Datastore Geo Point object.
| Parameter | |
|---|---|
| Name | Description |
coordinates | entity.CoordinatesCoordinate value. |
| Returns | |
|---|---|
| Type | Description |
entity.GeoPoint | {object} |
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 | |
|---|---|
| Type | Description |
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 | |
|---|---|
| Name | Description |
options | GetIndexesOptions |
| Returns | |
|---|---|
| Type | Description |
Promise<GetIndexesResponse> | |
getIndexes(options, callback)
getIndexes(options:GetIndexesOptions,callback:GetIndexesCallback):void;| Parameters | |
|---|---|
| Name | Description |
options | GetIndexesOptions |
callback | GetIndexesCallback |
| Returns | |
|---|---|
| Type | Description |
void | |
getIndexes(callback)
getIndexes(callback:GetIndexesCallback):void;| Parameter | |
|---|---|
| Name | Description |
callback | GetIndexesCallback |
| Returns | |
|---|---|
| Type | Description |
void | |
getIndexesStream(options)
getIndexesStream(options?:GetIndexesOptions):NodeJS.ReadableStream;Get all of the indexes in this project as a readable object stream.
| Parameter | |
|---|---|
| Name | Description |
options | GetIndexesOptionsConfiguration object. See for a complete list of options. |
| Returns | |
|---|---|
| Type | Description |
NodeJS.ReadableStream | {ReadableStream |
getProjectId()
getProjectId():Promise<string>;| Returns | |
|---|---|
| Type | Description |
Promise<string> | |
import(config)
import(config:ImportEntitiesConfig):Promise<LongRunningResponse>;Import entities into this project from a remote file.
| Parameter | |
|---|---|
| Name | Description |
config | ImportEntitiesConfigConfiguration object. |
| Returns | |
|---|---|
| Type | Description |
Promise<LongRunningResponse> | |
import(config, callback)
import(config:ImportEntitiesConfig,callback:LongRunningCallback):void;| Parameters | |
|---|---|
| Name | Description |
config | ImportEntitiesConfig |
callback | LongRunningCallback |
| Returns | |
|---|---|
| Type | Description |
void | |
index(id)
index(id:string):Index;Get a reference to an Index.
| Parameter | |
|---|---|
| Name | Description |
id | stringThe index name or id. |
| Returns | |
|---|---|
| Type | Description |
Index | {Index} |
insert(entities)
insert(entities:Entities):Promise<InsertResponse>;Maps toDatastore#save, forcing the method to beinsert.
| Parameter | |
|---|---|
| Name | Description |
entities | EntitiesDatastore key object(s). |
| Returns | |
|---|---|
| Type | Description |
Promise<InsertResponse> | |
insert(entities, callback)
insert(entities:Entities,callback:InsertCallback):void;| Parameters | |
|---|---|
| Name | Description |
entities | Entities |
callback | InsertCallback |
| Returns | |
|---|---|
| Type | Description |
void | |
int(value)
int(value:number|string):entity.Int;| Parameter | |
|---|---|
| Name | Description |
value | number | string |
| Returns | |
|---|---|
| Type | Description |
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 | |
|---|---|
| Name | Description |
value | number | stringThe integer value. |
| Returns | |
|---|---|
| Type | Description |
entity.Int | {object} |
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 | |
|---|---|
| Name | Description |
value | {} |
| Returns | |
|---|---|
| Type | Description |
value isentity.Double | |
isDouble(value)
staticisDouble(value?:{}):valueisentity.Double;Helper function to check if something is a Datastore Double object.
| Parameter | |
|---|---|
| Name | Description |
value | {} |
| Returns | |
|---|---|
| Type | Description |
value isentity.Double | {boolean} |
const{Datastore}=require('@google-cloud/datastore');constdatastore=newDatastore();datastore.isDouble(0.42);// falsedatastore.isDouble(datastore.double(0.42));// trueisGeoPoint(value)
isGeoPoint(value?:{}):valueisentity.GeoPoint;| Parameter | |
|---|---|
| Name | Description |
value | {} |
| Returns | |
|---|---|
| Type | Description |
value isentity.GeoPoint | |
isGeoPoint(value)
staticisGeoPoint(value?:{}):valueisentity.GeoPoint;Helper function to check if something is a Datastore Geo Point object.
| Parameter | |
|---|---|
| Name | Description |
value | {} |
| Returns | |
|---|---|
| Type | Description |
value isentity.GeoPoint | {boolean} |
const{Datastore}=require('@google-cloud/datastore');constdatastore=newDatastore();constcoordinates={latitude:0,longitude:0};datastore.isGeoPoint(coordinates);// falsedatastore.isGeoPoint(datastore.geoPoint(coordinates));// trueisInt(value)
isInt(value?:{}):valueisentity.Int;| Parameter | |
|---|---|
| Name | Description |
value | {} |
| Returns | |
|---|---|
| Type | Description |
value isentity.Int | |
isInt(value)
staticisInt(value?:{}):valueisentity.Int;Helper function to check if something is a Datastore Integer object.
| Parameter | |
|---|---|
| Name | Description |
value | {} |
| Returns | |
|---|---|
| Type | Description |
value isentity.Int | {boolean} |
const{Datastore}=require('@google-cloud/datastore');constdatastore=newDatastore();datastore.isInt(42);// falsedatastore.isInt(datastore.int(42));// trueisKey(value)
isKey(value?:{}):valueisentity.Key;| Parameter | |
|---|---|
| Name | Description |
value | {} |
| Returns | |
|---|---|
| Type | Description |
value isentity.Key | |
isKey(value)
staticisKey(value?:{}):valueisentity.Key;Helper function to check if something is a Datastore Key object.
| Parameter | |
|---|---|
| Name | Description |
value | {} |
| Returns | |
|---|---|
| Type | Description |
value isentity.Key | {boolean} |
const{Datastore}=require('@google-cloud/datastore');constdatastore=newDatastore();datastore.isKey({path:['Company',123]});// falsedatastore.isKey(datastore.key(['Company',123]));// truekey(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 | |
|---|---|
| Name | Description |
options | entity.KeyOptionsKey path. To specify or override a namespace, you must use an object here to explicitly state it. |
| Returns | |
|---|---|
| Type | Description |
Key | {Key} A newly created Key from the options given. |
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 | |
|---|---|
| Name | Description |
path | PathType[] |
| Returns | |
|---|---|
| Type | Description |
Key | |
key(path)
key(path:string):entity.Key;| Parameter | |
|---|---|
| Name | Description |
path | string |
| Returns | |
|---|---|
| Type | Description |
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 | |
|---|---|
| Name | Description |
key | stringEntity key object. |
| Returns | |
|---|---|
| Type | Description |
Key | {string} Created urlsafe key. |
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 | |
|---|---|
| Name | Description |
key | KeyEntity key object. |
locationPrefix | stringOptional . The location prefix of an App Engine project ID. Often this value is 's~', but may also be 'e~', or other location prefixes currently unknown. |
| Returns | |
|---|---|
| Type | Description |
Promise<string> | |
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 | |
|---|---|
| Name | Description |
key | Key |
callback | KeyToLegacyUrlSafeCallback |
| Returns | |
|---|---|
| Type | Description |
void | |
keyToLegacyUrlSafe(key, locationPrefix, callback)
keyToLegacyUrlSafe(key:entity.Key,locationPrefix:string,callback:KeyToLegacyUrlSafeCallback):void;| Parameters | |
|---|---|
| Name | Description |
key | Key |
locationPrefix | string |
callback | KeyToLegacyUrlSafeCallback |
| Returns | |
|---|---|
| Type | Description |
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 | |
|---|---|
| Name | Description |
entities | EntitiesDatastore key object(s). |
gaxOptions | CallOptionsRequest configuration options, outlined here: https://googleapis.github.io/gax-nodejs/global.html#CallOptions. |
| Returns | |
|---|---|
| Type | Description |
Promise<SaveResponse> | |
//-// 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 | |
|---|---|
| Name | Description |
entities | Entities |
gaxOptions | CallOptions |
callback | SaveCallback |
| Returns | |
|---|---|
| Type | Description |
void | |
save(entities, callback)
save(entities:Entities,callback:SaveCallback):void;| Parameters | |
|---|---|
| Name | Description |
entities | Entities |
callback | SaveCallback |
| Returns | |
|---|---|
| Type | Description |
void | |
transaction(options)
transaction(options?:TransactionOptions):Transaction;Create a new Transaction object.
| Parameter | |
|---|---|
| Name | Description |
options | TransactionOptionsConfiguration object. |
| Returns | |
|---|---|
| Type | Description |
Transaction | {Transaction} |
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 | |
|---|---|
| Name | Description |
entities | EntitiesDatastore key object(s). |
| Returns | |
|---|---|
| Type | Description |
Promise<UpdateResponse> | |
update(entities, callback)
update(entities:Entities,callback:UpdateCallback):void;| Parameters | |
|---|---|
| Name | Description |
entities | Entities |
callback | UpdateCallback |
| Returns | |
|---|---|
| Type | Description |
void | |
upsert(entities)
upsert(entities:Entities):Promise<UpsertResponse>;Maps toDatastore#save, forcing the method to beupsert.
| Parameter | |
|---|---|
| Name | Description |
entities | EntitiesDatastore key object(s). |
| Returns | |
|---|---|
| Type | Description |
Promise<UpsertResponse> | |
upsert(entities, callback)
upsert(entities:Entities,callback:UpsertCallback):void;| Parameters | |
|---|---|
| Name | Description |
entities | Entities |
callback | UpsertCallback |
| Returns | |
|---|---|
| Type | Description |
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.