Constructor

Firestore

new Firestore(settings)

Parameter

settings

Optional

Object

Configuration object.

Values in settings have the following properties:

Parameter

projectId

Optional

string

The Firestore Project ID. Can be omitted in environments that support Application Default Credentials {@see https://cloud.google.com/docs/authentication}

keyFilename

Optional

string

Local file containing the Service Account credentials. Can be omitted in environments that support Application Default Credentials {@see https://cloud.google.com/docs/authentication}

timestampsInSnapshots

Optional

boolean

Enables the use of Timestamps for timestamp fields in DocumentSnapshots.
Currently, Firestore returns timestamp fields as Date but Date only supports millisecond precision, which leads to truncation and causes unexpected behavior when using a timestamp from a snapshot as a part of a subsequent query.
Setting timestampsInSnapshots to true will cause Firestore to return Timestamp values instead of Date avoiding this kind of problem. To make this work you must also change any code that uses Date to use Timestamp instead.
NOTE: in the future timestampsInSnapshots: true will become the default and this option will be removed so you should change your code to use Timestamp now and opt-in to this new behavior as soon as you can.

See also

Firestore Documentation

Examples

<caption>Install the client library with <a
href="https://www.npmjs.com/">npm</a>:</caption> npm install --save

Import the client library

var Firestore = require('@google-cloud/firestore');
<caption>Create a client that uses <a
href="https://cloud.google.com/docs/authentication/production#providing_credentials_to_your_application">Application
Default Credentials (ADC)</a>:</caption> var firestore = new Firestore();
<caption>Create a client with <a
href="https://cloud.google.com/docs/authentication/production#obtaining_and_providing_service_account_credentials_manually">explicit
credentials</a>:</caption> var firestore = new Firestore({ projectId:
'your-project-id', keyFilename: '/path/to/keyfile.json'
});

Full quickstart example:

const Firestore = require('@google-cloud/firestore');

const firestore = new Firestore({
  projectId: 'YOUR_PROJECT_ID',
  keyFilename: '/path/to/keyfile.json',
});

const document = firestore.doc('posts/intro-to-firestore');

// Enter new data into the document.
document.set({
  title: 'Welcome to Firestore',
  body: 'Hello World',
}).then(() => {
  // Document created successfully.
});

// Update an existing document.
document.update({
  body: 'My first Firestore app',
}).then(() => {
  // Document updated successfully.
});

// Read the document.
document.get().then(doc => {
  // Document read successfully.
});

// Delete the document.
document.delete().then(() => {
  // Document deleted successfully.
});

Properties

CollectionReference

static

CollectionReference

CollectionReference class.

See also
CollectionReference

DocumentChange

static

DocumentChange

DocumentChange class.

See also
DocumentChange

DocumentReference

static

DocumentReference

DocumentReference class.

See also
DocumentReference

DocumentSnapshot

static

DocumentSnapshot

DocumentSnapshot DocumentSnapshot.

See also
DocumentSnapshot

FieldPath

static

Constructor

FieldPath class.

See also
FieldPath

FieldValue

static

FieldValue class.

See also
FieldValue

GeoPoint

static

Constructor

GeoPoint class.

See also
GeoPoint

Query

static

Query

Query class.

See also
Query

QueryDocumentSnapshot

static

QueryDocumentSnapshot

QueryDocumentSnapshot class.

See also
QueryDocumentSnapshot

QuerySnapshot

static

QuerySnapshot

QuerySnapshot class.

See also
QuerySnapshot

Timestamp

static

Timestamp

Timestamp class.

See also
Timestamp

Transaction

static

Transaction

Transaction class.

See also
Transaction

v1beta1

static

function()

v1beta1 factory function.

See also
v1beta1

WriteBatch

static

WriteBatch

WriteBatch class.

See also
WriteBatch

WriteResult

static

WriteResult

WriteResult class.

See also
WriteResult

Methods

setLogFunction

static

setLogFunction(logger)

Sets the log function for all active Firestore instances.

Parameter

logger

Firestore~logFunction

A log function that takes a single string.

batch

batch() returns WriteBatch

Creates a WriteBatch, used for performing multiple writes as a single atomic operation.

Returns

WriteBatch 

A WriteBatch that operates on this Firestore client.

Example

let writeBatch = firestore.batch();

// Add two documents in an atomic batch.
let data = { foo: 'bar' };
writeBatch.set(firestore.doc('col/doc1'), data);
writeBatch.set(firestore.doc('col/doc2'), data);

writeBatch.commit().then(res => {
  console.log(`Added document at ${res.writeResults[0].updateTime}`);
});

collection

collection(collectionPath) returns CollectionReference

Gets a CollectionReference instance that refers to the collection at the specified path.

Parameter

collectionPath

string

A slash-separated path to a collection.

Returns

CollectionReference 

The CollectionReference instance.

Example

let collectionRef = firestore.collection('collection');

// Add a document with an auto-generated ID.
collectionRef.add({foo: 'bar'}).then((documentRef) => {
  console.log(`Added document at ${documentRef.path})`);
});

doc

doc(documentPath) returns DocumentReference

Gets a DocumentReference instance that refers to the document at the specified path.

Parameter

documentPath

string

A slash-separated path to a document.

Returns

DocumentReference 

The DocumentReference instance.

Example

let documentRef = firestore.doc('collection/document');
console.log(`Path of document is ${documentRef.path}`);

getAll

getAll(...documents) returns Promise containing Array of DocumentSnapshot

Retrieves multiple documents from Firestore.

Parameter

documents

DocumentReference

The document references to receive.

Value may be repeated.

Returns

Promise containing Array of DocumentSnapshot 

A Promise that contains an array with the resulting document snapshots.

Example

let documentRef1 = firestore.doc('col/doc1');
let documentRef2 = firestore.doc('col/doc2');

firestore.getAll(documentRef1, documentRef2).then(docs => {
  console.log(`First document: ${JSON.stringify(docs[0])}`);
  console.log(`Second document: ${JSON.stringify(docs[1])}`);
});

getCollections

getCollections() returns Promise containing Array of CollectionReference

Fetches the root collections that are associated with this Firestore database.

Returns

Promise containing Array of CollectionReference 

A Promise that resolves with an array of CollectionReferences.

Example

firestore.getCollections().then(collections => {
  for (let collection of collections) {
    console.log(`Found collection with id: ${collection.id}`);
  }
});

runTransaction

runTransaction(updateFunction, transactionOptions) returns Promise

Executes the given updateFunction and commits the changes applied within the transaction.

You can use the transaction object passed to 'updateFunction' to read and modify Firestore documents under lock. Transactions are committed once 'updateFunction' resolves and attempted up to five times on failure.

Parameter

updateFunction

function(Transaction)

The function to execute within the transaction context.

transactionOptions

Optional

object

Transaction options.

Values in transactionOptions have the following properties:

Parameter

maxAttempts

Optional

number

The maximum number of attempts for this transaction.

Returns

Promise 

If the transaction completed successfully or was explicitly aborted (by the updateFunction returning a failed Promise), the Promise returned by the updateFunction will be returned here. Else if the transaction failed, a rejected Promise with the corresponding failure error will be returned.

Example

let counterTransaction = firestore.runTransaction(transaction => {
  let documentRef = firestore.doc('col/doc');
  return transaction.get(documentRef).then(doc => {
    if (doc.exists) {
      let count =  doc.get('count') || 0;
      if (count > 10) {
        return Promise.reject('Reached maximum count');
      }
      transaction.update(documentRef, { count: ++count });
      return Promise.resolve(count);
    }

    transaction.create(documentRef, { count: 1 });
    return Promise.resolve(1);
  });
});

counterTransaction.then(res => {
  console.log(`Count updated to ${res}`);
});

settings

settings(settings)

Specifies custom settings to be used to configure the Firestore instance. Can only be invoked once and before any other Firestore method.

If settings are provided via both settings() and the Firestore constructor, both settings objects are merged and any settings provided via settings() take precedence.

Parameter

settings

object

The settings to use for all Firestore operations.

Abstract type

logFunction

inner

logFunction(Log)

A logging function that takes a single string.

Parameter

Log

string

message