The Cloud Firestore service interface.
Do not call this constructor directly. Instead, usefirebase.firestore().
Index
Constructors
Private constructor
Properties
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 of
FieldValue.serverTimestamp(),FieldValue.arrayUnion(),FieldValue.arrayRemove(), orFieldValue.increment()inside a WriteBatch counts as an additional write.ReturnsWriteBatch
A
WriteBatchthat can be used to atomically execute multiple writes.
clearPersistence
- clear
Persistence():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 of
failed-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
- collection(collectionPath: string):CollectionReference<DocumentData>
Gets a
CollectionReferenceinstance that refers to the collection atthe specified path.Parameters
collectionPath:string
A slash-separated path to a collection.
ReturnsCollectionReference<DocumentData>
The
CollectionReferenceinstance.
collectionGroup
- collection
Group(collectionId: string):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
- disable
Network():Promise<void> Disables network usage for this instance. It can be re-enabled via
enableNetwork(). 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
- doc(documentPath: string):DocumentReference<DocumentData>
Gets a
DocumentReferenceinstance that refers to the document at thespecified path.Parameters
documentPath:string
A slash-separated path to a document.
ReturnsDocumentReference<DocumentData>
The
DocumentReferenceinstance.
enableNetwork
- enable
Network():Promise<void> Re-enables use of the network for this Firestore instance after a priorcall to
disableNetwork().ReturnsPromise<void>
A promise that is resolved once the network has beenenabled.
enablePersistence
- enable
Persistence(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 bythe
codeon the error.- failed-precondition: The app is already open in another browser tab.
- unimplemented: The browser is incompatible with the offlinepersistence implementation.
Parameters
Optional settings:PersistenceSettings
Optional settings object to configure persistence.
ReturnsPromise<void>
A promise that represents successfully enabling persistentstorage.
loadBundle
- load
Bundle(bundleData: ArrayBuffer |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 are
ArrayBuffer,ReadableStream<Uint8Array>orstring.
ReturnsLoadBundleTask
A
LoadBundleTaskobject, which notifies callers with progress updates, and completionor error events. It can be used as aPromise<LoadBundleTaskProgress>.
namedQuery
- named
Query(name: string):Promise<Query<DocumentData> |null> Reads a Firestore
Queryfrom 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 using
loadBundle. Once in localcache, use this method to extract aQueryby name.Parameters
name:string
ReturnsPromise<Query<DocumentData> |null>
onSnapshotsInSync
- on
Snapshots InSync(observer: {complete?:() =>void;error?:(error: FirestoreError) =>void;next?:(value: void) =>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 containing
nextanderrorcallbacks.Optional complete?:() =>void
- ():void
Returnsvoid
Optional error?:(error:FirestoreError) =>void
- (error:FirestoreError):void
Parameters
error:FirestoreError
Returnsvoid
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
- on
Snapshots InSync(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
- run
Transaction<T>(updateFunction: (transaction: Transaction) =>Promise<T>):Promise<T> Executes the given
updateFunctionand 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 of
FieldValue.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.
- (transaction:Transaction):Promise<T>
Parameters
transaction:Transaction
ReturnsPromise<T>
ReturnsPromise<T>
If the transaction completed successfully or was explicitly aborted(the
updateFunctionreturned 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
terminate
- terminate():Promise<void>
Terminates this Firestore instance.
After calling
terminate()only theclearPersistence()method may be used. Any other methodwill throw aFirestoreError.To restart after termination, create a new instance of FirebaseFirestore with
firebase.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, calling
terminate()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
- use
Emulator(host: string, port: number, 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 }
Optional mock
User Token?:EmulatorMockTokenOptions |string the mock auth token to use for unittesting Security Rules.
Returnsvoid
waitForPendingWrites
- wait
For Pending Writes():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, call
waitForPendingWrites()again.Any outstanding
waitForPendingWrites()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.