Abstract type

new Firestore([settings])

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

include:samples/quickstart.js

region_tag:firestore_quickstart
Full quickstart example:

Parameters

Name Type Optional Description

settings

 

Yes

Configuration object.

Values in settings have the following properties:

Name Type Optional Description

projectId

 

Yes

The project ID from the Google Developer's Console, e.g. 'grape-spaceship-123'. We will also check the environment variable GCLOUD_PROJECT for your project ID. Can be omitted in environments that support Application Default Credentials

keyFilename

 

Yes

Local file containing the Service Account credentials as downloaded from the Google Developers Console. Can be omitted in environments that support Application Default Credentials. To configure Firestore with custom credentials, use settings.credentials and provide the client_email and private_key of your service account.

credentials

 

Yes

The client_email and private_key properties of the service account to use with your Firestore project. Can be omitted in environments that support Application Default Credentials. If your credentials are stored in a JSON file, you can specify a keyFilename instead.

host

 

Yes

The host to connect to.

ssl

 

Yes

Whether to use SSL when connecting.

timestampsInSnapshots

 

Yes

Specifies whether to use Timestamp objects for timestamp fields in DocumentSnapshots. This is enabled by default and should not be disabled.
Previously, Firestore returned 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.
So now Firestore returns Timestamp values instead of Date, avoiding this kind of problem.
To opt into the old behavior of returning Date objects, you can temporarily set timestampsInSnapshots to false.
WARNING: This setting will be removed in a future release. You should update your code to expect Timestamp objects and stop using the timestampsInSnapshots setting.

See also

Firestore Documentation

Methods

batch() → WriteBatch

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

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

WriteBatch 

A WriteBatch that operates on this Firestore client.

collection(collectionPath) → CollectionReference

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

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

Parameter

Name Type Optional Description

collectionPath

string

 

A slash-separated path to a collection.

Returns

CollectionReference 

The CollectionReference instance.

collectionGroup(collectionId) → Query

Creates and returns a new Query that includes all documents in the database that are contained in a collection or subcollection with the given collectionId.

Example

let docA = firestore.doc('mygroup/docA').set({foo: 'bar'});
let docB = firestore.doc('abc/def/mygroup/docB').set({foo: 'bar'});

Promise.all([docA, docB]).then(() => {
   let query = firestore.collectionGroup('mygroup');
   query = query.where('foo', '==', 'bar');
   return query.get().then(snapshot => {
      console.log(`Found ${snapshot.size} documents.`);
   });
});

Parameter

Name Type Optional Description

collectionId

string

 

Identifies the collections to query over. Every collection or subcollection with this ID as the last segment of its path will be included. Cannot contain a slash.

Returns

Query 

The created Query.

doc(documentPath) → DocumentReference

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

Example

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

Parameter

Name Type Optional Description

documentPath

string

 

A slash-separated path to a document.

Returns

DocumentReference 

The DocumentReference instance.

getAll(...documentRefsOrReadOptions) → Promise containing Array of DocumentSnapshot

Retrieves multiple documents from Firestore.

The first argument is required and must be of type DocumentReference followed by any additional DocumentReference documents. If used, the optional ReadOptions must be the last argument.

Example

let docRef1 = firestore.doc('col/doc1');
let docRef2 = firestore.doc('col/doc2');

firestore.getAll(docRef1, docRef2, { fieldMask: ['user'] }).then(docs => {
  console.log(`First document: ${JSON.stringify(docs[0])}`);
  console.log(`Second document: ${JSON.stringify(docs[1])}`);
});

Parameter

Name Type Optional Description

documentRefsOrReadOptions

(repeatable DocumentReference or ReadOptions)

 

The DocumentReferences to receive, followed by an optional field mask.

Value can be repeated.

Returns

Promise containing Array of DocumentSnapshot 

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

listCollections() → Promise containing Array of CollectionReference

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

Example

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

Promise containing Array of CollectionReference 

A Promise that resolves with an array of CollectionReferences.

runTransaction(updateFunction[, transactionOptions]) → 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.

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

Parameters

Name Type Optional Description

updateFunction

function(Transaction)

 

The function to execute within the transaction context.

transactionOptions

object

Yes

Transaction options.

Values in transactionOptions have the following properties:

Name Type Optional Description

maxAttempts

number

Yes

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.

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

Name Type Optional Description

settings

object

 

The settings to use for all Firestore operations.

Abstract type

inner

logFunction(Log)

A logging function that takes a single string.

Parameter

Name Type Optional Description

Log

string

 

message