Class Datastore (6.6.2)

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_ID is recognized. If you have this set, you don't need to provide a projectId .

See Cloud 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 uses Application Default Credentials (ADC) :

 const datastore = new Datastore(); 

Create a client with explicit credentials :

 const datastore = new Datastore({
  projectId: 'your-project-id',
  keyFilename: '/path/to/keyfile.json'
}); 

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];
}); 

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);
  });
}); 

Creating Records

 // New entities can be created and persisted with {@link Datastore#save}.
// The entitiy 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.
  }
}); 

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.
  }
}); 

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.
      }
    });
  });
}); 

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']); // child
entity const cookieKey3 = datastore. key 
(['Customer', customerId2, 'Cookie',
'cookie93911']); // child entity

const 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);
}); 

Constructors

(constructor)(options)

  constructor 
 ( 
 options 
 ?: 
  
 DatastoreOptions 
 ); 
 

Constructs a new instance of the Datastore class

Parameter
Name
Description

Properties

auth

  auth 
 : 
  
 GoogleAuth 
 ; 
 
Property Value
Type
Description
GoogleAuth

baseUrl_

  baseUrl_ 
 ?: 
  
 string 
 ; 
 
Property Value
Type
Description
string

clients_

  clients_ 
 : 
  
 Map<string 
 , 
  
 ClientStub 
> ; 
 
Property Value
Type
Description
Map <string, ClientStub >

customEndpoint_

  customEndpoint_ 
 ?: 
  
 boolean 
 ; 
 
Property Value
Type
Description
boolean

DatastoreRequest

  DatastoreRequest 
 : 
  
 typeof 
  
 DatastoreRequest 
 ; 
 

DatastoreRequest class.

Datastore.DatastoreRequest

Property Value
Type
Description
typeof DatastoreRequest

defaultBaseUrl_

  defaultBaseUrl_ 
 : 
  
 string 
 ; 
 
Property Value
Type
Description
string

KEY

  KEY 
 : 
  
 typeof 
  
 entity 
 . 
 KEY_SYMBOL 
 ; 
 
Property Value
Type
Description
typeof entity.KEY_SYMBOL

KEY

  static 
  
 KEY 
 : 
  
 typeof 
  
 entity 
 . 
 KEY_SYMBOL 
 ; 
 

Access the Key from an Entity object.

Datastore#KEY {symbol}

Property Value
Type
Description
typeof entity.KEY_SYMBOL

MORE_RESULTS_AFTER_CURSOR

  MORE_RESULTS_AFTER_CURSOR 
 : 
  
 string 
 ; 
 
Property Value
Type
Description
string

MORE_RESULTS_AFTER_CURSOR

  static 
  
 MORE_RESULTS_AFTER_CURSOR 
 : 
  
 string 
 ; 
 

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

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

{string}

Property Value
Type
Description
string

MORE_RESULTS_AFTER_LIMIT

  MORE_RESULTS_AFTER_LIMIT 
 : 
  
 string 
 ; 
 
Property Value
Type
Description
string

MORE_RESULTS_AFTER_LIMIT

  static 
  
 MORE_RESULTS_AFTER_LIMIT 
 : 
  
 string 
 ; 
 

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

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

{string}

Property Value
Type
Description
string

namespace

  namespace 
 ?: 
  
 string 
 ; 
 
Property Value
Type
Description
string

NO_MORE_RESULTS

  NO_MORE_RESULTS 
 : 
  
 string 
 ; 
 
Property Value
Type
Description
string

NO_MORE_RESULTS

  static 
  
 NO_MORE_RESULTS 
 : 
  
 string 
 ; 
 

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

There are no more results left to query for.

{string}

Property Value
Type
Description
string

options

  options 
 : 
  
 DatastoreOptions 
 ; 
 
Property Value
Type
Description

port_

  port_ 
 ?: 
  
 number 
 ; 
 
Property Value
Type
Description
number

Query

  Query 
 : 
  
 typeof 
  
 Query 
 ; 
 

Query class.

Datastore.Query

Property Value
Type
Description
typeof Query

Transaction

  Transaction 
 : 
  
 typeof 
  
 Transaction 
 ; 
 

Transaction class.

Datastore.Transaction

Property Value
Type
Description
typeof Transaction

Methods

createQuery(kind)

  createQuery 
 ( 
 kind 
 ?: 
  
 string 
 ) 
 : 
  
 Query 
 ; 
 

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

Parameter
Name
Description
kind
string

The kind to query.

Returns
Type
Description
Query

{Query}

Example
 const {Datastore} = require(' @google-cloud/datastore 
');
const datastore = new Datastore 
();
const query = 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
string

Custom 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)

  static 
  
 double 
 ( 
 value 
 : 
  
 number 
 ) 
 : 
  
 entity 
 . 
 Double 
 ; 
 

Helper function to get a Datastore Double object.

Parameter
Name
Description
value
number

The double value.

Returns
Type
Description
entity.Double

{object}

Example
 const {Datastore} = require(' @google-cloud/datastore 
');
const datastore = new Datastore 
();
const threeDouble = 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
ExportEntitiesConfig

Configuration object.

Returns
Type
Description
Promise < LongRunningResponse >

export(config, callback)

  export 
 ( 
 config 
 : 
  
 ExportEntitiesConfig 
 , 
  
 callback 
 : 
  
 LongRunningCallback 
 ) 
 : 
  
 void 
 ; 
 
Parameters
Name
Description
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)

  static 
  
 geoPoint 
 ( 
 coordinates 
 : 
  
 entity 
 . 
 Coordinates 
 ) 
 : 
  
 entity 
 . 
 GeoPoint 
 ; 
 

Helper function to get a Datastore Geo Point object.

Parameter
Name
Description
coordinates
entity.Coordinates

Coordinate value.

Returns
Type
Description
entity.GeoPoint

{object}

Example
 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)); 

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
GetIndexesOptions

Configuration 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
ImportEntitiesConfig

Configuration object.

Returns
Type
Description
Promise < LongRunningResponse >

import(config, callback)

  import 
 ( 
 config 
 : 
  
 ImportEntitiesConfig 
 , 
  
 callback 
 : 
  
 LongRunningCallback 
 ) 
 : 
  
 void 
 ; 
 
Parameters
Name
Description
Returns
Type
Description
void

index(id)

  index 
 ( 
 id 
 : 
  
 string 
 ) 
 : 
  
 Index 
 ; 
 

Get a reference to an Index.

Parameter
Name
Description
id
string

The index name or id.

Returns
Type
Description

{Index}

insert(entities)

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

Maps to , forcing the method to be insert .

Parameter
Name
Description
entities
Entities

Datastore key object(s).

Returns
Type
Description
Promise < InsertResponse >

insert(entities, callback)

  insert 
 ( 
 entities 
 : 
  
 Entities 
 , 
  
 callback 
 : 
  
 InsertCallback 
 ) 
 : 
  
 void 
 ; 
 
Parameters
Name
Description
entities
Entities
callback
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)

  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
Name
Description
value
number | string

The integer value.

Returns
Type
Description
entity.Int

{object}

Example
 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')
]); 

isDouble(value)

  isDouble 
 ( 
 value 
 ?: 
  
 {}) 
 : 
  
 boolean 
 ; 
 
Parameter
Name
Description
value
{}
Returns
Type
Description
boolean

isDouble(value)

  static 
  
 isDouble 
 ( 
 value 
 ?: 
  
 {}) 
 : 
  
 boolean 
 ; 
 

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

Parameter
Name
Description
value
{}
Returns
Type
Description
boolean

{boolean}

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

isGeoPoint(value)

  isGeoPoint 
 ( 
 value 
 ?: 
  
 {}) 
 : 
  
 boolean 
 ; 
 
Parameter
Name
Description
value
{}
Returns
Type
Description
boolean

isGeoPoint(value)

  static 
  
 isGeoPoint 
 ( 
 value 
 ?: 
  
 {}) 
 : 
  
 boolean 
 ; 
 

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

Parameter
Name
Description
value
{}
Returns
Type
Description
boolean

{boolean}

Example
 const {Datastore} = require(' @google-cloud/datastore 
');
const datastore = new Datastore 
();
const coordinates = {
  latitude: 0,
  longitude: 0
};

datastore. isGeoPoint 
(coordinates); // false
datastore. isGeoPoint 
(datastore. geoPoint 
(coordinates)); // true 

isInt(value)

  isInt 
 ( 
 value 
 ?: 
  
 {}) 
 : 
  
 boolean 
 ; 
 
Parameter
Name
Description
value
{}
Returns
Type
Description
boolean

isInt(value)

  static 
  
 isInt 
 ( 
 value 
 ?: 
  
 {}) 
 : 
  
 boolean 
 ; 
 

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

Parameter
Name
Description
value
{}
Returns
Type
Description
boolean

{boolean}

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

isKey(value)

  isKey 
 ( 
 value 
 ?: 
  
 {}) 
 : 
  
 boolean 
 ; 
 
Parameter
Name
Description
value
{}
Returns
Type
Description
boolean

isKey(value)

  static 
  
 isKey 
 ( 
 value 
 ?: 
  
 {}) 
 : 
  
 boolean 
 ; 
 

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

Parameter
Name
Description
value
{}
Returns
Type
Description
boolean

{boolean}

Example
 const {Datastore} = require(' @google-cloud/datastore 
');
const datastore = new Datastore 
();
datastore. isKey 
({path: ['Company', 123]}); // false
datastore. 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
Name
Description
options
KeyOptions

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

Examples
 <caption>Create an incomplete key with a kind value of `Company`.
Since no Id is supplied, Datastore will generate one on save.</caption>
const {Datastore} = require(' @google-cloud/datastore 
');
const datastore = new Datastore 
();
const key = datastore. key 
('Company'); 
 <caption>Create a complete key with a kind value of `Company` and Id `123`.</caption>
const {Datastore} = require(' @google-cloud/datastore 
');
const datastore = new Datastore 
();
const key = datastore. key 
(['Company', 123]); 
 <caption>If the ID integer is outside the bounds of a JavaScript Number
object, create an Int.</caption>
const {Datastore} = require(' @google-cloud/datastore 
');
const datastore = new Datastore 
();
const key = datastore. key 
([
  'Company',
  datastore. int 
('100000000000001234')
]); 
 <caption>Create a complete key with a kind value of `Company` and name `Google`.
Because the supplied Id is a string, Datastore will prefix it with "name=".
Had the supplied Id been numeric, Datastore would prefix it with the standard, "id=".</caption>
const {Datastore} = require(' @google-cloud/datastore 
');
const datastore = new Datastore 
();
const key = datastore. key 
(['Company', 'Google']); 
 <caption>Create a complete key from a provided namespace and path.</caption>
const {Datastore} = require(' @google-cloud/datastore 
');
const datastore = new Datastore 
();
const key = datastore. key 
({
  namespace: 'My-NS',
  path: ['Company', 123]
}); 
 <caption>Create a complete key that specifies an ancestor. This will create a Team entity
with a name of " Datastore 
", which belongs to the Company with the "name=Google" key.</caption>
const {Datastore} = require(' @google-cloud/datastore 
');
const datastore = new Datastore 
();
const key = datastore. key 
(['Company', 'Google', 'Team', ' Datastore 
']); 
 <caption>Create a incomplete key that specifies an ancestor. This will create an Employee entity
with an auto-generated Id, which belongs to the Company with the "name=Google" key.</caption>
const {Datastore} = require(' @google-cloud/datastore 
');
const datastore = new Datastore 
();
const key = datastore. key 
(['Company', 'Google', 'Employee']); 

key(path)

  key 
 ( 
 path 
 : 
  
 PathType 
 []) 
 : 
  
 entity 
 . 
 Key 
 ; 
 
Parameter
Name
Description
path
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
string

Entity key object.

Returns
Type
Description
Key

{string} Created urlsafe key.

Example
 const {Datastore} = require(' @google-cloud/datastore 
');
const datastore = new Datastore 
();
const urlSafeKey = '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
Key

Entity key object.

locationPrefix
string

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
Type
Description
Promise <string>
Example
 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);
}); 

keyToLegacyUrlSafe(key, callback)

  keyToLegacyUrlSafe 
 ( 
 key 
 : 
  
 entity 
 . 
 Key 
 , 
  
 callback 
 : 
  
 KeyToLegacyUrlSafeCallback 
 ) 
 : 
  
 void 
 ; 
 
Parameters
Name
Description
key
Key
Returns
Type
Description
void

keyToLegacyUrlSafe(key, locationPrefix, callback)

  keyToLegacyUrlSafe 
 ( 
 key 
 : 
  
 entity 
 . 
 Key 
 , 
  
 locationPrefix 
 : 
  
 string 
 , 
  
 callback 
 : 
  
 KeyToLegacyUrlSafeCallback 
 ) 
 : 
  
 void 
 ; 
 
Parameters
Name
Description
key
Key
locationPrefix
string
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 , or update ) by using the key(s) provided. For example, if you provide an incomplete key (one without an ID), the request will create a new entity and have its ID automatically assigned. If you provide a complete key, the entity will be updated with the data specified.

By default, all properties are indexed. To prevent a property from being included in *all* indexes, you must supply an excludeFromIndexes array.

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

as save

Parameters
Name
Description
entities
Entities

Datastore key object(s).

gaxOptions
CallOptions

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

Returns
Type
Description
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.
//-
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];
}); 

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
TransactionOptions

Configuration object.

Returns
Type
Description
Transaction

{Transaction}

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

update(entities)

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

Maps to , forcing the method to be update .

Parameter
Name
Description
entities
Entities

Datastore key object(s).

Returns
Type
Description
Promise < UpdateResponse >

update(entities, callback)

  update 
 ( 
 entities 
 : 
  
 Entities 
 , 
  
 callback 
 : 
  
 UpdateCallback 
 ) 
 : 
  
 void 
 ; 
 
Parameters
Name
Description
entities
Entities
callback
Returns
Type
Description
void

upsert(entities)

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

Maps to , forcing the method to be upsert .

Parameter
Name
Description
entities
Entities

Datastore key object(s).

Returns
Type
Description
Promise < UpsertResponse >

upsert(entities, callback)

  upsert 
 ( 
 entities 
 : 
  
 Entities 
 , 
  
 callback 
 : 
  
 UpsertCallback 
 ) 
 : 
  
 void 
 ; 
 
Parameters
Name
Description
entities
Entities
callback
Returns
Type
Description
void
Create a Mobile Website
View Site in Mobile | Classic
Share by: