Firestore

Firestore

The Firestore client represents a Firestore Database and is the entry point for all Firestore operations.

Constructor

new Firestore(settingsopt)

Parameters:
Name Type Attributes Description
settings Object <optional>

Configuration object.

Properties
Name Type Attributes Description
projectId string <optional>

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 string <optional>

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 Object <optional>

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 string <optional>

The host to connect to.

ssl boolean <optional>

Whether to use SSL when connecting.

maxIdleChannels number <optional>

The maximum number of idle GRPC channels to keep. A smaller number of idle channels reduces memory usage but increases request latency for clients with fluctuating request rates. If set to 0, shuts down all GRPC channels when the client becomes idle. Defaults to 1.

ignoreUndefinedProperties boolean <optional>

Whether to skip nested properties that are set to undefined during object serialization. If set to true, these properties are skipped and not written to Firestore. If set false or omitted, the SDK throws an exception when it encounters properties of type undefined.

See:
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');

// Create a new client
const firestore = new Firestore();

async function quickstart() {
  // Obtain a document reference.
  const document = firestore.doc('posts/intro-to-firestore');

  // Enter new data into the document.
  await document.set({
    title: 'Welcome to Firestore',
    body: 'Hello World',
  });
  console.log('Entered new data into the document');

  // Update an existing document.
  await document.update({
    body: 'My first Firestore app',
  });
  console.log('Updated an existing document');

  // Read the document.
  const doc = await document.get();
  console.log('Read the document');

  // Delete the document.
  await document.delete();
  console.log('Deleted the document');
}
quickstart();

Methods

batch() → {WriteBatch}

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

Returns:
Type Description
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('Successfully executed batch.');
});

bulkWriter(optionsopt) → {BulkWriter}

Creates a BulkWriter, used for performing multiple writes in parallel. Gradually ramps up writes as specified by the 500/50/5 rule.

If you pass BulkWriterOptions, you can configure the throttling rates for the created BulkWriter.

Parameters:
Name Type Attributes Description
options BulkWriterOptions <optional>

BulkWriter options.

Returns:
Type Description
BulkWriter

A BulkWriter that operates on this Firestore client.

See:
Example
let bulkWriter = firestore.bulkWriter();

bulkWriter.create(firestore.doc('col/doc1'), {foo: 'bar'})
  .then(res => {
    console.log(`Added document at ${res.writeTime}`);
  });
bulkWriter.update(firestore.doc('col/doc2'), {foo: 'bar'})
  .then(res => {
    console.log(`Updated document at ${res.writeTime}`);
  });
bulkWriter.delete(firestore.doc('col/doc3'))
  .then(res => {
    console.log(`Deleted document at ${res.writeTime}`);
  });
await bulkWriter.close().then(() => {
  console.log('Executed all writes');
});

bundle()

Creates a new BundleBuilder instance to package selected Firestore data into a bundle.

Parameters:
Name Type Description
bundleId.

The id of the bundle. When loaded on clients, client SDKs use this id and the timestamp associated with the built bundle to tell if it has been loaded already. If not specified, a random identifier will be used.

collection(collectionPath) → {CollectionReference}

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

Parameters:
Name Type Description
collectionPath string

A slash-separated path to a collection.

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

collectionGroup(collectionId) → {CollectionGroup}

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.

Parameters:
Name Type 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:
Type Description
CollectionGroup

The created CollectionGroup.

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

doc(documentPath) → {DocumentReference}

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

Parameters:
Name Type Description
documentPath string

A slash-separated path to a document.

Returns:
Type Description
DocumentReference

The DocumentReference instance.

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

getAll(…documentRefsOrReadOptions) → {Promise.<Array.<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.

Parameters:
Name Type Attributes Description
documentRefsOrReadOptions DocumentReference | ReadOptions <repeatable>

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

Returns:
Type Description
Promise.<Array.<DocumentSnapshot>>

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

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

listCollections() → {Promise.<Array.<CollectionReference>>}

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

Returns:
Type Description
Promise.<Array.<CollectionReference>>

A Promise that resolves with an array of CollectionReferences.

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

recursiveDelete(ref, bulkWriter)

Recursively deletes all documents and subcollections at and under the specified level.

If any delete fails, the promise is rejected with an error message containing the number of failed deletes and the stack trace of the last failed delete. The provided reference is deleted regardless of whether all deletes succeeded.

recursiveDelete() uses a BulkWriter instance with default settings to perform the deletes. To customize throttling rates or add success/error callbacks, pass in a custom BulkWriter instance.

Parameters:
Name Type Description
ref

The reference of a document or collection to delete.

bulkWriter

A custom BulkWriter instance used to perform the deletes.

Returns:
Type Description

A promise that resolves when all deletes have been performed. The promise is rejected if any of the deletes fail.

Example
// Recursively delete a reference and log the references of failures.
const bulkWriter = firestore.bulkWriter();
bulkWriter
  .onWriteError((error) => {
    if (
      error.failedAttempts < MAX_RETRY_ATTEMPTS
    ) {
      return true;
    } else {
      console.log('Failed write at document: ', error.documentRef.path);
      return false;
    }
  });
await firestore.recursiveDelete(docRef, bulkWriter);

runTransaction(updateFunction, transactionOptions) → {Promise.<T>}

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. You have to perform all reads before before you perform any write.

Transactions can be performed as read-only or read-write transactions. By default, transactions are executed in read-write mode.

A read-write transaction obtains a pessimistic lock on all documents that are read during the transaction. These locks block other transactions, batched writes, and other non-transactional writes from changing that document. Any writes in a read-write transactions are committed once 'updateFunction' resolves, which also releases all locks.

If a read-write transaction fails with contention, the transaction is retried up to five times. The updateFunction is invoked once for each attempt.

Read-only transactions do not lock documents. They can be used to read documents at a consistent snapshot in time, which may be up to 60 seconds in the past. Read-only transactions are not retried.

Transactions time out after 60 seconds if no documents are read. Transactions that are not committed within than 270 seconds are also aborted. Any remaining locks are released when a transaction times out.

Parameters:
Name Type Description
updateFunction Firestore~updateFunction

The user function to execute within the transaction context.

transactionOptions Firestore~ReadWriteTransactionOptions | Firestore~ReadOnlyTransactionOptions

Transaction options.

Returns:
Type Description
Promise.<T>

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)

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.

Parameters:
Name Type Description
settings object

The settings to use for all Firestore operations.

terminate()

Terminates the Firestore client and closes all open streams.

Returns:
Type Description

A Promise that resolves when the client is terminated.

toJSON()

Returns the Project ID to serve as the JSON representation of this Firestore instance.

Returns:
Type Description

An object that contains the project ID (or undefined if not yet available).

Type Definitions

logFunction(Log)

A logging function that takes a single string.

Parameters:
Name Type Description
Log string

message

ReadOnlyTransactionOptions(readOnly, readTimeopt)

Options object for Firestore#runTransaction to configure a read-only transaction.

Parameters:
Name Type Attributes Description
readOnly true

Set to true to indicate a read-only transaction.

readTime Timestamp <optional>

If specified, documents are read at the given time. This may not be more than 60 seconds in the past from when the request is processed by the server.

ReadWriteTransactionOptions(readOnlyopt, maxAttemptsopt)

Options object for Firestore#runTransaction to configure a read-write transaction.

Parameters:
Name Type Attributes Description
readOnly false <optional>

Set to false or omit to indicate a read-write transaction.

maxAttempts number <optional>

The maximum number of attempts for this transaction. Defaults to five.

updateFunction(transaction) → {Promise.<T>}

Function executed by Firestore#runTransaction within the transaction context.

Parameters:
Name Type Description
transaction Transaction

The transaction object for this transaction.

Returns:
Type Description
Promise.<T>

The promise returned at the end of the transaction. This promise will be returned by Firestore#runTransaction if the transaction completed successfully.