The Cloud Firestore service interface.

Do not call this constructor directly. Instead, usefirebase.firestore().

Index

Constructors

Private constructor

Properties

app

app:App

Theapp associated with thisFirestore serviceinstance.

Methods

batch

  • batch():WriteBatch
  • Creates a write batch, used for performing multiple writes as a singleatomic operation. The maximum number of writes allowed in a single WriteBatchis 500, but note that each usage ofFieldValue.serverTimestamp(),FieldValue.arrayUnion(),FieldValue.arrayRemove(), orFieldValue.increment() inside a WriteBatch counts as an additional write.

    ReturnsWriteBatch

    AWriteBatch that can be used to atomically execute multiple writes.

clearPersistence

  • clearPersistence():Promise<void>
  • Clears the persistent storage. This includes pending writes and cacheddocuments.

    Must be called while the firestore instance is not started (after the appis shutdown or when the app is first initialized). On startup, thismethod must be called before other methods (other than settings()). Ifthe firestore instance is still running, the promise will be rejectedwith the error code offailed-precondition.

    Note: clearPersistence() is primarily intended to help write reliabletests that use Cloud Firestore. It uses an efficient mechanism fordropping existing data but does not attempt to securely overwrite orotherwise make cached data unrecoverable. For applications that aresensitive to the disclosure of cached data in between user sessions, westrongly recommend not enabling persistence at all.

    ReturnsPromise<void>

    A promise that is resolved when the persistent storage iscleared. Otherwise, the promise is rejected with an error.

collection

collectionGroup

  • collectionGroup(collectionIdstring):Query<DocumentData>
  • Creates and returns a new Query that includes all documents in thedatabase that are contained in a collection or subcollection with thegiven collectionId.

    Parameters

    • collectionId:string

      Identifies the collections to query over. Everycollection or subcollection with this ID as the last segment of its pathwill be included. Cannot contain a slash.

    ReturnsQuery<DocumentData>

    The created Query.

disableNetwork

  • disableNetwork():Promise<void>
  • Disables network usage for this instance. It can be re-enabled viaenableNetwork(). Whilethe network is disabled, any snapshot listeners or get() calls will returnresults from cache, and any write operations will be queued until the networkis restored.

    ReturnsPromise<void>

    A promise that is resolved once the network has beendisabled.

doc

enableNetwork

  • enableNetwork():Promise<void>
  • Re-enables use of the network for this Firestore instance after a priorcall todisableNetwork().

    ReturnsPromise<void>

    A promise that is resolved once the network has beenenabled.

enablePersistence

  • enablePersistence(settings?: PersistenceSettings):Promise<void>
  • Attempts to enable persistent storage, if possible.

    Must be called before any other methods (other than settings() andclearPersistence()).

    If this fails, enablePersistence() will reject the promise it returns.Note that even after this failure, the firestore instance will remainusable, however offline persistence will be disabled.

    There are several reasons why this can fail, which can be identified bythecode on the error.

    • failed-precondition: The app is already open in another browser tab.
    • unimplemented: The browser is incompatible with the offlinepersistence implementation.

    Parameters

    ReturnsPromise<void>

    A promise that represents successfully enabling persistentstorage.

loadBundle

  • loadBundle(bundleDataArrayBuffer |ReadableStream<Uint8Array> |string):LoadBundleTask
  • Loads a Firestore bundle into the local cache.

    Parameters

    • bundleData:ArrayBuffer |ReadableStream<Uint8Array> |string

      An object representing the bundle to be loaded. Valid objects areArrayBuffer,ReadableStream<Uint8Array> orstring.

    ReturnsLoadBundleTask

    ALoadBundleTask object, which notifies callers with progress updates, and completionor error events. It can be used as aPromise<LoadBundleTaskProgress>.

namedQuery

  • namedQuery(namestring):Promise<Query<DocumentData> |null>
  • Reads a FirestoreQuery from local cache, identified by the given name.

    The named queries are packaged into bundles on the server side (alongwith resulting documents), and loaded to local cache usingloadBundle. Once in localcache, use this method to extract aQuery by name.

    Parameters

    • name:string

    ReturnsPromise<Query<DocumentData> |null>

onSnapshotsInSync

  • onSnapshotsInSync(observer{complete?:() =>void;error?:(errorFirestoreError) =>void;next?:(valuevoid) =>void }):() =>void
  • Attaches a listener for a snapshots-in-sync event. The snapshots-in-syncevent indicates that all listeners affected by a given change have fired,even if a single server-generated change affects multiple listeners.

    NOTE: The snapshots-in-sync event only indicates that listeners are in syncwith each other, but does not relate to whether those snapshots are in syncwith the server. Use SnapshotMetadata in the individual listeners todetermine if a snapshot is from the cache or the server.

    Parameters

    • observer:{complete?:() =>void;error?:(error:FirestoreError) =>void;next?:(value:void) =>void }

      A single object containingnext anderror callbacks.

      • Optional complete?:() =>void
          • ():void
          • Returnsvoid

      • Optional error?:(error:FirestoreError) =>void
      • Optional next?:(value:void) =>void
          • (value:void):void
          • Parameters

            • value:void

            Returnsvoid

    Returns() =>void

    An unsubscribe function that can be called to cancel the snapshotlistener.

      • ():void
      • Returnsvoid

  • onSnapshotsInSync(onSync() =>void):() =>void
  • Attaches a listener for a snapshots-in-sync event. The snapshots-in-syncevent indicates that all listeners affected by a given change have fired,even if a single server-generated change affects multiple listeners.

    NOTE: The snapshots-in-sync event only indicates that listeners are in syncwith each other, but does not relate to whether those snapshots are in syncwith the server. Use SnapshotMetadata in the individual listeners todetermine if a snapshot is from the cache or the server.

    Parameters

    • onSync:() =>void

      A callback to be called every time all snapshot listeners arein sync with each other.

        • ():void
        • Returnsvoid

    Returns() =>void

    An unsubscribe function that can be called to cancel the snapshotlistener.

      • ():void
      • Returnsvoid

runTransaction

  • runTransaction<T>(updateFunction(transactionTransaction) =>Promise<T>):Promise<T>
  • Executes the givenupdateFunction and then attempts to commit the changesapplied within the transaction. If any document read within the transactionhas changed, Cloud Firestore retries theupdateFunction. If it fails tocommit after 5 attempts, the transaction fails.

    The maximum number of writes allowed in a single transaction is 500, butnote that each usage ofFieldValue.serverTimestamp(),FieldValue.arrayUnion(),FieldValue.arrayRemove(), orFieldValue.increment() inside a transaction counts as an additional write.

    Type parameters

    • T

    Parameters

    • updateFunction:(transaction:Transaction) =>Promise<T>

      The function to execute within the transaction context.

    ReturnsPromise<T>

    If the transaction completed successfully or was explicitly aborted(theupdateFunction returned a failed promise),the promise returned by the updateFunction is returned here. Else, if thetransaction failed, a rejected promise with the corresponding failureerror will be returned.

settings

  • settings(settingsSettings):void
  • Specifies custom settings to be used to configure theFirestoreinstance. Must be set before invoking any other methods.

    Parameters

    Returnsvoid

terminate

  • terminate():Promise<void>
  • Terminates this Firestore instance.

    After callingterminate() only theclearPersistence() method may be used. Any other methodwill throw aFirestoreError.

    To restart after termination, create a new instance of FirebaseFirestore withfirebase.firestore().

    Termination does not cancel any pending writes, and any promises that are awaiting a responsefrom the server will not be resolved. If you have persistence enabled, the next time youstart this instance, it will resume sending these writes to the server.

    Note: Under normal circumstances, callingterminate() is not required. Thismethod is useful only when you want to force this instance to release all of its resources orin combination withclearPersistence() to ensure that all local state is destroyedbetween test runs.

    ReturnsPromise<void>

    A promise that is resolved when the instance has been successfully terminated.

useEmulator

  • useEmulator(hoststring, portnumber, options?: {mockUserToken?:EmulatorMockTokenOptions |string }):void
  • Modify this instance to communicate with the Cloud Firestore emulator.

    Note: this must be called before this instance has been used to do any operations.

    Parameters

    • host:string

      the emulator host (ex: localhost).

    • port:number

      the emulator port (ex: 9000).

    • Optional options:{mockUserToken?:EmulatorMockTokenOptions |string }

    Returnsvoid

waitForPendingWrites

  • waitForPendingWrites():Promise<void>
  • Waits until all currently pending writes for the active user have been acknowledged by thebackend.

    The returned Promise resolves immediately if there are no outstanding writes. Otherwise, thePromise waits for all previously issued writes (including those written in a previous appsession), but it does not wait for writes that were added after the method is called. If youwant to wait for additional writes, callwaitForPendingWrites() again.

    Any outstandingwaitForPendingWrites() Promises are rejected during user changes.

    ReturnsPromise<void>

    A Promise which resolves when all currently pending writes have beenacknowledged by the backend.

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 2022-07-27 UTC.