@firebase/firestore
- Version 4.7.6
- Published
- 28.2 MB
- 7 dependencies
- Apache-2.0 license
Install
npm i @firebase/firestore
yarn add @firebase/firestore
pnpm add @firebase/firestore
Overview
Cloud Firestore
Index
Variables
Functions
- addDoc()
- aggregateFieldEqual()
- aggregateQuerySnapshotEqual()
- and()
- arrayRemove()
- arrayUnion()
- average()
- clearIndexedDbPersistence()
- collection()
- collectionGroup()
- connectFirestoreEmulator()
- count()
- deleteAllPersistentCacheIndexes()
- deleteDoc()
- deleteField()
- disableNetwork()
- disablePersistentCacheIndexAutoCreation()
- doc()
- documentId()
- enableIndexedDbPersistence()
- enableMultiTabIndexedDbPersistence()
- enableNetwork()
- enablePersistentCacheIndexAutoCreation()
- endAt()
- endBefore()
- getAggregateFromServer()
- getCountFromServer()
- getDoc()
- getDocFromCache()
- getDocFromServer()
- getDocs()
- getDocsFromCache()
- getDocsFromServer()
- getFirestore()
- getPersistentCacheIndexManager()
- increment()
- initializeFirestore()
- limit()
- limitToLast()
- loadBundle()
- memoryEagerGarbageCollector()
- memoryLocalCache()
- memoryLruGarbageCollector()
- namedQuery()
- onSnapshot()
- onSnapshotsInSync()
- or()
- orderBy()
- persistentLocalCache()
- persistentMultipleTabManager()
- persistentSingleTabManager()
- query()
- queryEqual()
- refEqual()
- runTransaction()
- serverTimestamp()
- setDoc()
- setIndexConfiguration()
- setLogLevel()
- snapshotEqual()
- startAfter()
- startAt()
- sum()
- terminate()
- updateDoc()
- vector()
- waitForPendingWrites()
- where()
- writeBatch()
Classes
Interfaces
Type Aliases
- AddPrefixToKeys
- AggregateFieldType
- AggregateSpecData
- AggregateType
- ChildUpdateFields
- DocumentChangeType
- FirestoreErrorCode
- FirestoreLocalCache
- ListenSource
- MemoryGarbageCollector
- NestedUpdateFields
- OrderByDirection
- PartialWithFieldValue
- PersistentTabManager
- Primitive
- QueryConstraintType
- QueryFilterConstraint
- QueryNonFilterConstraint
- SetOptions
- TaskState
- UnionToIntersection
- UpdateData
- WhereFilterOp
- WithFieldValue
Variables
variable CACHE_SIZE_UNLIMITED
const CACHE_SIZE_UNLIMITED: number;
Constant used to indicate the LRU garbage collection should be disabled. Set this value as the
cacheSizeBytes
on the settings passed to the Firestore instance.
Functions
function addDoc
addDoc: <AppModelType, DbModelType extends DocumentData>( reference: CollectionReference<AppModelType, DbModelType>, data: WithFieldValue<AppModelType>) => Promise<DocumentReference<AppModelType, DbModelType>>;
Add a new document to specified
CollectionReference
with the given data, assigning it a document ID automatically.Parameter reference
A reference to the collection to add this document to.
Parameter data
An Object containing the data for the new document.
Returns
A
Promise
resolved with aDocumentReference
pointing to the newly created document after it has been written to the backend (Note that it won't resolve while you're offline).
function aggregateFieldEqual
aggregateFieldEqual: ( left: AggregateField<unknown>, right: AggregateField<unknown>) => boolean;
Compares two 'AggregateField` instances for equality.
Parameter left
Compare this AggregateField to the
right
.Parameter right
Compare this AggregateField to the
left
.
function aggregateQuerySnapshotEqual
aggregateQuerySnapshotEqual: < AggregateSpecType extends AggregateSpec, AppModelType, DbModelType extends DocumentData>( left: AggregateQuerySnapshot<AggregateSpecType, AppModelType, DbModelType>, right: AggregateQuerySnapshot<AggregateSpecType, AppModelType, DbModelType>) => boolean;
Compares two
AggregateQuerySnapshot
instances for equality.Two
AggregateQuerySnapshot
instances are considered "equal" if they have underlying queries that compare equal, and the same data.Parameter left
The first
AggregateQuerySnapshot
to compare.Parameter right
The second
AggregateQuerySnapshot
to compare.Returns
true
if the objects are "equal", as defined above, orfalse
otherwise.
function and
and: ( ...queryConstraints: QueryFilterConstraint[]) => QueryCompositeFilterConstraint;
Creates a new QueryCompositeFilterConstraint that is a conjunction of the given filter constraints. A conjunction filter includes a document if it satisfies all of the given filters.
Parameter queryConstraints
Optional. The list of QueryFilterConstraints to perform a conjunction for. These must be created with calls to where, or, or and.
Returns
The newly created QueryCompositeFilterConstraint.
function arrayRemove
arrayRemove: (...elements: unknown[]) => FieldValue;
Returns a special value that can be used with setDoc or that tells the server to remove the given elements from any array value that already exists on the server. All instances of each element specified will be removed from the array. If the field being modified is not already an array it will be overwritten with an empty array.
Parameter elements
The elements to remove from the array.
Returns
The
FieldValue
sentinel for use in a call tosetDoc()
orupdateDoc()
function arrayUnion
arrayUnion: (...elements: unknown[]) => FieldValue;
Returns a special value that can be used with @firebase/firestore#setDoc or @firebase/firestore#updateDoc that tells the server to union the given elements with any array value that already exists on the server. Each specified element that doesn't already exist in the array will be added to the end. If the field being modified is not already an array it will be overwritten with an array containing exactly the specified elements.
Parameter elements
The elements to union into the array.
Returns
The
FieldValue
sentinel for use in a call tosetDoc()
orupdateDoc()
.
function average
average: (field: string | FieldPath) => AggregateField<number | null>;
Create an AggregateField object that can be used to compute the average of a specified field over a range of documents in the result set of a query.
Parameter field
Specifies the field to average across the result set.
function clearIndexedDbPersistence
clearIndexedDbPersistence: (firestore: Firestore) => Promise<void>;
Clears the persistent storage. This includes pending writes and cached documents.
Must be called while the Firestore instance is not started (after the app is terminated or when the app is first initialized). On startup, this function must be called before other functions (other than initializeFirestore or getFirestore)). If the Firestore instance is still running, the promise will be rejected with the error code of
failed-precondition
.Note:
clearIndexedDbPersistence()
is primarily intended to help write reliable tests that use Cloud Firestore. It uses an efficient mechanism for dropping existing data but does not attempt to securely overwrite or otherwise make cached data unrecoverable. For applications that are sensitive to the disclosure of cached data in between user sessions, we strongly recommend not enabling persistence at all.Parameter firestore
The Firestore instance to clear persistence for.
Returns
A
Promise
that is resolved when the persistent storage is cleared. Otherwise, the promise is rejected with an error.
function collection
collection: { ( firestore: Firestore, path: string, ...pathSegments: string[] ): CollectionReference<DocumentData, DocumentData>; <AppModelType, DbModelType extends DocumentData>( reference: CollectionReference<AppModelType, DbModelType>, path: string, ...pathSegments: string[] ): CollectionReference<DocumentData, DocumentData>; <AppModelType, DbModelType extends DocumentData>( reference: DocumentReference<AppModelType, DbModelType>, path: string, ...pathSegments: string[] ): CollectionReference<DocumentData, DocumentData>;};
Gets a
CollectionReference
instance that refers to the collection at the specified absolute path.Parameter firestore
A reference to the root
Firestore
instance.Parameter path
A slash-separated path to a collection.
Parameter pathSegments
Additional path segments to apply relative to the first argument.
Returns
The
CollectionReference
instance.Throws
If the final path has an even number of segments and does not point to a collection.
Gets a
CollectionReference
instance that refers to a subcollection ofreference
at the specified relative path.Parameter reference
A reference to a collection.
Parameter path
A slash-separated path to a collection.
Parameter pathSegments
Additional path segments to apply relative to the first argument.
Returns
The
CollectionReference
instance.Throws
If the final path has an even number of segments and does not point to a collection.
Gets a
CollectionReference
instance that refers to a subcollection ofreference
at the specified relative path.Parameter reference
A reference to a Firestore document.
Parameter path
A slash-separated path to a collection.
Parameter pathSegments
Additional path segments that will be applied relative to the first argument.
Returns
The
CollectionReference
instance.Throws
If the final path has an even number of segments and does not point to a collection.
function collectionGroup
collectionGroup: ( firestore: Firestore, collectionId: string) => Query<DocumentData, DocumentData>;
Creates and returns a new
Query
instance that includes all documents in the database that are contained in a collection or subcollection with the givencollectionId
.Parameter firestore
A reference to the root
Firestore
instance.Parameter collectionId
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
The created
Query
.
function connectFirestoreEmulator
connectFirestoreEmulator: ( firestore: Firestore, 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.
Parameter firestore
The
Firestore
instance to configure to connect to the emulator.Parameter host
the emulator host (ex: localhost).
Parameter port
the emulator port (ex: 9000).
Parameter
options.mockUserToken - the mock auth token to use for unit testing Security Rules.
function count
count: () => AggregateField<number>;
Create an AggregateField object that can be used to compute the count of documents in the result set of a query.
function deleteAllPersistentCacheIndexes
deleteAllPersistentCacheIndexes: ( indexManager: PersistentCacheIndexManager) => void;
Removes all persistent cache indexes.
Please note this function will also deletes indexes generated by
setIndexConfiguration()
, which is deprecated.
function deleteDoc
deleteDoc: <AppModelType, DbModelType extends DocumentData>( reference: DocumentReference<AppModelType, DbModelType>) => Promise<void>;
Deletes the document referred to by the specified
DocumentReference
.Parameter reference
A reference to the document to delete.
Returns
A Promise resolved once the document has been successfully deleted from the backend (note that it won't resolve while you're offline).
function deleteField
deleteField: () => FieldValue;
Returns a sentinel for use with @firebase/firestore#updateDoc or @firebase/firestore#setDoc with
{merge: true}
to mark a field for deletion.
function disableNetwork
disableNetwork: (firestore: Firestore) => Promise<void>;
Disables network usage for this instance. It can be re-enabled via enableNetwork. While the network is disabled, any snapshot listeners,
getDoc()
orgetDocs()
calls will return results from cache, and any write operations will be queued until the network is restored.Returns
A
Promise
that is resolved once the network has been disabled.
function disablePersistentCacheIndexAutoCreation
disablePersistentCacheIndexAutoCreation: ( indexManager: PersistentCacheIndexManager) => void;
Stops creating persistent cache indexes automatically for local query execution. The indexes which have been created by calling
enablePersistentCacheIndexAutoCreation()
still take effect.
function doc
doc: { ( firestore: Firestore, path: string, ...pathSegments: string[] ): DocumentReference<DocumentData, DocumentData>; <AppModelType, DbModelType extends DocumentData>( reference: CollectionReference<AppModelType, DbModelType>, path?: string, ...pathSegments: string[] ): DocumentReference<AppModelType, DbModelType>; <AppModelType, DbModelType extends DocumentData>( reference: DocumentReference<AppModelType, DbModelType>, path: string, ...pathSegments: string[] ): DocumentReference<DocumentData, DocumentData>;};
Gets a
DocumentReference
instance that refers to the document at the specified absolute path.Parameter firestore
A reference to the root
Firestore
instance.Parameter path
A slash-separated path to a document.
Parameter pathSegments
Additional path segments that will be applied relative to the first argument.
Returns
The
DocumentReference
instance.Throws
If the final path has an odd number of segments and does not point to a document.
Gets a
DocumentReference
instance that refers to a document withinreference
at the specified relative path. If no path is specified, an automatically-generated unique ID will be used for the returnedDocumentReference
.Parameter reference
A reference to a collection.
Parameter path
A slash-separated path to a document. Has to be omitted to use auto-generated IDs.
Parameter pathSegments
Additional path segments that will be applied relative to the first argument.
Returns
The
DocumentReference
instance.Throws
If the final path has an odd number of segments and does not point to a document.
Gets a
DocumentReference
instance that refers to a document withinreference
at the specified relative path.Parameter reference
A reference to a Firestore document.
Parameter path
A slash-separated path to a document.
Parameter pathSegments
Additional path segments that will be applied relative to the first argument.
Returns
The
DocumentReference
instance.Throws
If the final path has an odd number of segments and does not point to a document.
function documentId
documentId: () => FieldPath;
Returns a special sentinel
FieldPath
to refer to the ID of a document. It can be used in queries to sort or filter by the document ID.
function enableIndexedDbPersistence
enableIndexedDbPersistence: ( firestore: Firestore, persistenceSettings?: PersistenceSettings) => Promise<void>;
Attempts to enable persistent storage, if possible.
On failure,
enableIndexedDbPersistence()
will reject the promise or throw an exception. There are several reasons why this can fail, which can be identified by thecode
on the error.* failed-precondition: The app is already open in another browser tab. * unimplemented: The browser is incompatible with the offline persistence implementation.
Note that even after a failure, the Firestore instance will remain usable, however offline persistence will be disabled.
Note:
enableIndexedDbPersistence()
must be called before any other functions (other than initializeFirestore, getFirestore or clearIndexedDbPersistence.Persistence cannot be used in a Node.js environment.
Parameter firestore
The Firestore instance to enable persistence for.
Parameter persistenceSettings
Optional settings object to configure persistence.
Returns
A
Promise
that represents successfully enabling persistent storage.Deprecated
This function will be removed in a future major release. Instead, set
FirestoreSettings.localCache
to an instance ofPersistentLocalCache
to turn on IndexedDb cache. Calling this function whenFirestoreSettings.localCache
is already specified will throw an exception.
function enableMultiTabIndexedDbPersistence
enableMultiTabIndexedDbPersistence: (firestore: Firestore) => Promise<void>;
Attempts to enable multi-tab persistent storage, if possible. If enabled across all tabs, all operations share access to local persistence, including shared execution of queries and latency-compensated local document updates across all connected instances.
On failure,
enableMultiTabIndexedDbPersistence()
will reject the promise or throw an exception. There are several reasons why this can fail, which can be identified by thecode
on the error.* failed-precondition: The app is already open in another browser tab and multi-tab is not enabled. * unimplemented: The browser is incompatible with the offline persistence implementation.
Note that even after a failure, the Firestore instance will remain usable, however offline persistence will be disabled.
Parameter firestore
The Firestore instance to enable persistence for.
Returns
A
Promise
that represents successfully enabling persistent storage.Deprecated
This function will be removed in a future major release. Instead, set
FirestoreSettings.localCache
to an instance ofPersistentLocalCache
to turn on indexeddb cache. Calling this function whenFirestoreSettings.localCache
is already specified will throw an exception.
function enableNetwork
enableNetwork: (firestore: Firestore) => Promise<void>;
Re-enables use of the network for this Firestore instance after a prior call to disableNetwork.
Returns
A
Promise
that is resolved once the network has been enabled.
function enablePersistentCacheIndexAutoCreation
enablePersistentCacheIndexAutoCreation: ( indexManager: PersistentCacheIndexManager) => void;
Enables the SDK to create persistent cache indexes automatically for local query execution when the SDK believes cache indexes can help improve performance.
This feature is disabled by default.
function endAt
endAt: { <AppModelType, DbModelType extends DocumentData>( snapshot: DocumentSnapshot<AppModelType, DbModelType> ): QueryEndAtConstraint; (...fieldValues: unknown[]): QueryEndAtConstraint;};
Creates a QueryEndAtConstraint that modifies the result set to end at the provided document (inclusive). The end position is relative to the order of the query. The document must contain all of the fields provided in the orderBy of the query.
Parameter snapshot
The snapshot of the document to end at.
Returns
A QueryEndAtConstraint to pass to
query()
Creates a QueryEndAtConstraint that modifies the result set to end at the provided fields relative to the order of the query. The order of the field values must match the order of the order by clauses of the query.
Parameter fieldValues
The field values to end this query at, in order of the query's order by.
Returns
A QueryEndAtConstraint to pass to
query()
function endBefore
endBefore: { <AppModelType, DbModelType extends DocumentData>( snapshot: DocumentSnapshot<AppModelType, DbModelType> ): QueryEndAtConstraint; (...fieldValues: unknown[]): QueryEndAtConstraint;};
Creates a QueryEndAtConstraint that modifies the result set to end before the provided document (exclusive). The end position is relative to the order of the query. The document must contain all of the fields provided in the orderBy of the query.
Parameter snapshot
The snapshot of the document to end before.
Returns
A QueryEndAtConstraint to pass to
query()
Creates a QueryEndAtConstraint that modifies the result set to end before the provided fields relative to the order of the query. The order of the field values must match the order of the order by clauses of the query.
Parameter fieldValues
The field values to end this query before, in order of the query's order by.
Returns
A QueryEndAtConstraint to pass to
query()
function getAggregateFromServer
getAggregateFromServer: < AggregateSpecType extends AggregateSpec, AppModelType, DbModelType extends DocumentData>( query: Query<AppModelType, DbModelType>, aggregateSpec: AggregateSpecType) => Promise<AggregateQuerySnapshot<AggregateSpecType, AppModelType, DbModelType>>;
Calculates the specified aggregations over the documents in the result set of the given query without actually downloading the documents.
Using this function to perform aggregations is efficient because only the final aggregation values, not the documents' data, are downloaded. This function can perform aggregations of the documents in cases where the result set is prohibitively large to download entirely (thousands of documents).
The result received from the server is presented, unaltered, without considering any local state. That is, documents in the local cache are not taken into consideration, neither are local modifications not yet synchronized with the server. Previously-downloaded results, if any, are not used. Every invocation of this function necessarily involves a round trip to the server.
Parameter query
The query whose result set is aggregated over.
Parameter aggregateSpec
An
AggregateSpec
object that specifies the aggregates to perform over the result set. The AggregateSpec specifies aliases for each aggregate, which can be used to retrieve the aggregate result.Example 1
const aggregateSnapshot = await getAggregateFromServer(query, {countOfDocs: count(),totalHours: sum('hours'),averageScore: average('score')});const countOfDocs: number = aggregateSnapshot.data().countOfDocs;const totalHours: number = aggregateSnapshot.data().totalHours;const averageScore: number | null = aggregateSnapshot.data().averageScore;
function getCountFromServer
getCountFromServer: <AppModelType, DbModelType extends DocumentData>( query: Query<AppModelType, DbModelType>) => Promise< AggregateQuerySnapshot< { count: AggregateField<number> }, AppModelType, DbModelType >>;
Calculates the number of documents in the result set of the given query without actually downloading the documents.
Using this function to count the documents is efficient because only the final count, not the documents' data, is downloaded. This function can count the documents in cases where the result set is prohibitively large to download entirely (thousands of documents).
The result received from the server is presented, unaltered, without considering any local state. That is, documents in the local cache are not taken into consideration, neither are local modifications not yet synchronized with the server. Previously-downloaded results, if any, are not used. Every invocation of this function necessarily involves a round trip to the server.
Parameter query
The query whose result set size is calculated.
Returns
A Promise that will be resolved with the count; the count can be retrieved from
snapshot.data().count
, wheresnapshot
is theAggregateQuerySnapshot
to which the returned Promise resolves.
function getDoc
getDoc: <AppModelType, DbModelType extends DocumentData>( reference: DocumentReference<AppModelType, DbModelType>) => Promise<DocumentSnapshot<AppModelType, DbModelType>>;
Reads the document referred to by this
DocumentReference
.Note:
getDoc()
attempts to provide up-to-date data when possible by waiting for data from the server, but it may return cached data or fail if you are offline and the server cannot be reached. To specify this behavior, invoke getDocFromCache or getDocFromServer.Parameter reference
The reference of the document to fetch.
Returns
A Promise resolved with a
DocumentSnapshot
containing the current document contents.
function getDocFromCache
getDocFromCache: <AppModelType, DbModelType extends DocumentData>( reference: DocumentReference<AppModelType, DbModelType>) => Promise<DocumentSnapshot<AppModelType, DbModelType>>;
Reads the document referred to by this
DocumentReference
from cache. Returns an error if the document is not currently cached.Returns
A
Promise
resolved with aDocumentSnapshot
containing the current document contents.
function getDocFromServer
getDocFromServer: <AppModelType, DbModelType extends DocumentData>( reference: DocumentReference<AppModelType, DbModelType>) => Promise<DocumentSnapshot<AppModelType, DbModelType>>;
Reads the document referred to by this
DocumentReference
from the server. Returns an error if the network is not available.Returns
A
Promise
resolved with aDocumentSnapshot
containing the current document contents.
function getDocs
getDocs: <AppModelType, DbModelType extends DocumentData>( query: Query<AppModelType, DbModelType>) => Promise<QuerySnapshot<AppModelType, DbModelType>>;
Executes the query and returns the results as a
QuerySnapshot
.Note:
getDocs()
attempts to provide up-to-date data when possible by waiting for data from the server, but it may return cached data or fail if you are offline and the server cannot be reached. To specify this behavior, invoke getDocsFromCache or getDocsFromServer.Returns
A
Promise
that will be resolved with the results of the query.
function getDocsFromCache
getDocsFromCache: <AppModelType, DbModelType extends DocumentData>( query: Query<AppModelType, DbModelType>) => Promise<QuerySnapshot<AppModelType, DbModelType>>;
Executes the query and returns the results as a
QuerySnapshot
from cache. Returns an empty result set if no documents matching the query are currently cached.Returns
A
Promise
that will be resolved with the results of the query.
function getDocsFromServer
getDocsFromServer: <AppModelType, DbModelType extends DocumentData>( query: Query<AppModelType, DbModelType>) => Promise<QuerySnapshot<AppModelType, DbModelType>>;
Executes the query and returns the results as a
QuerySnapshot
from the server. Returns an error if the network is not available.Returns
A
Promise
that will be resolved with the results of the query.
function getFirestore
getFirestore: { (): Firestore; (app: FirebaseApp): Firestore; (databaseId: string): Firestore; (app: FirebaseApp, databaseId: string): Firestore;};
Returns the existing default Firestore instance that is associated with the default @firebase/app#FirebaseApp. If no instance exists, initializes a new instance with default settings.
Returns
The default Firestore instance of the default app.
Returns the existing default Firestore instance that is associated with the provided @firebase/app#FirebaseApp. If no instance exists, initializes a new instance with default settings.
Parameter app
The @firebase/app#FirebaseApp instance that the returned Firestore instance is associated with.
Returns
The default Firestore instance of the provided app.
Returns the existing named Firestore instance that is associated with the default @firebase/app#FirebaseApp. If no instance exists, initializes a new instance with default settings.
Parameter databaseId
The name of the database.
Returns
The named Firestore instance of the default app.
Modifiers
@beta
Returns the existing named Firestore instance that is associated with the provided @firebase/app#FirebaseApp. If no instance exists, initializes a new instance with default settings.
Parameter app
The @firebase/app#FirebaseApp instance that the returned Firestore instance is associated with.
Parameter databaseId
The name of the database.
Returns
The named Firestore instance of the provided app.
Modifiers
@beta
function getPersistentCacheIndexManager
getPersistentCacheIndexManager: ( firestore: Firestore) => PersistentCacheIndexManager | null;
Returns the PersistentCache Index Manager used by the given
Firestore
object.The
PersistentCacheIndexManager
instance, ornull
if local persistent storage is not in use.
function increment
increment: (n: number) => FieldValue;
Returns a special value that can be used with @firebase/firestore#setDoc or @firebase/firestore#updateDoc that tells the server to increment the field's current value by the given value.
If either the operand or the current field value uses floating point precision, all arithmetic follows IEEE 754 semantics. If both values are integers, values outside of JavaScript's safe number range (
Number.MIN_SAFE_INTEGER
toNumber.MAX_SAFE_INTEGER
) are also subject to precision loss. Furthermore, once processed by the Firestore backend, all integer operations are capped between -2^63 and 2^63-1.If the current field value is not of type
number
, or if the field does not yet exist, the transformation sets the field to the given value.Parameter n
The value to increment by.
Returns
The
FieldValue
sentinel for use in a call tosetDoc()
orupdateDoc()
function initializeFirestore
initializeFirestore: ( app: FirebaseApp, settings: FirestoreSettings, databaseId?: string) => Firestore;
Initializes a new instance of Firestore with the provided settings. Can only be called before any other function, including getFirestore. If the custom settings are empty, this function is equivalent to calling getFirestore.
Parameter app
The @firebase/app#FirebaseApp with which the Firestore instance will be associated.
Parameter settings
A settings object to configure the Firestore instance.
Parameter databaseId
The name of the database.
Returns
A newly initialized Firestore instance.
function limit
limit: (limit: number) => QueryLimitConstraint;
Creates a QueryLimitConstraint that only returns the first matching documents.
Parameter limit
The maximum number of items to return.
Returns
The created QueryLimitConstraint.
function limitToLast
limitToLast: (limit: number) => QueryLimitConstraint;
Creates a QueryLimitConstraint that only returns the last matching documents.
You must specify at least one
orderBy
clause forlimitToLast
queries, otherwise an exception will be thrown during execution.Parameter limit
The maximum number of items to return.
Returns
The created QueryLimitConstraint.
function loadBundle
loadBundle: ( firestore: Firestore, bundleData: ReadableStream<Uint8Array> | ArrayBuffer | string) => LoadBundleTask;
Loads a Firestore bundle into the local cache.
Parameter firestore
The Firestore instance to load bundles for.
Parameter bundleData
An object representing the bundle to be loaded. Valid objects are
ArrayBuffer
,ReadableStream<Uint8Array>
orstring
.Returns
A
LoadBundleTask
object, which notifies callers with progress updates, and completion or error events. It can be used as aPromise<LoadBundleTaskProgress>
.
function memoryEagerGarbageCollector
memoryEagerGarbageCollector: () => MemoryEagerGarbageCollector;
Creates an instance of
MemoryEagerGarbageCollector
. This is also the default garbage collector unless it is explicitly specified otherwise.
function memoryLocalCache
memoryLocalCache: (settings?: MemoryCacheSettings) => MemoryLocalCache;
Creates an instance of
MemoryLocalCache
. The instance can be set toFirestoreSettings.cache
to tell the SDK which cache layer to use.
function memoryLruGarbageCollector
memoryLruGarbageCollector: (settings?: { cacheSizeBytes?: number;}) => MemoryLruGarbageCollector;
Creates an instance of
MemoryLruGarbageCollector
.A target size can be specified as part of the setting parameter. The collector will start deleting documents once the cache size exceeds the given size. The default cache size is 40MB (40 * 1024 * 1024 bytes).
function namedQuery
namedQuery: (firestore: Firestore, name: string) => Promise<Query | null>;
Reads a Firestore Query from local cache, identified by the given name.
The named queries are packaged into bundles on the server side (along with resulting documents), and loaded to local cache using
loadBundle
. Once in local cache, use this method to extract a Query by name.Parameter firestore
The Firestore instance to read the query from.
Parameter name
The name of the query.
Returns
A
Promise
that is resolved with the Query ornull
.
function onSnapshot
onSnapshot: { <AppModelType, DbModelType extends DocumentData>( reference: DocumentReference<AppModelType, DbModelType>, observer: { next?: (snapshot: DocumentSnapshot<AppModelType, DbModelType>) => void; error?: (error: FirestoreError) => void; complete?: () => void; } ): Unsubscribe; <AppModelType, DbModelType extends DocumentData>( reference: DocumentReference<AppModelType, DbModelType>, options: SnapshotListenOptions, observer: { next?: (snapshot: DocumentSnapshot<AppModelType, DbModelType>) => void; error?: (error: FirestoreError) => void; complete?: () => void; } ): Unsubscribe; <AppModelType, DbModelType extends DocumentData>( reference: DocumentReference<AppModelType, DbModelType>, onNext: (snapshot: DocumentSnapshot<AppModelType, DbModelType>) => void, onError?: (error: FirestoreError) => void, onCompletion?: () => void ): Unsubscribe; <AppModelType, DbModelType extends DocumentData>( reference: DocumentReference<AppModelType, DbModelType>, options: SnapshotListenOptions, onNext: (snapshot: DocumentSnapshot<AppModelType, DbModelType>) => void, onError?: (error: FirestoreError) => void, onCompletion?: () => void ): Unsubscribe; <AppModelType, DbModelType extends DocumentData>( query: Query<AppModelType, DbModelType>, observer: { next?: (snapshot: QuerySnapshot<AppModelType, DbModelType>) => void; error?: (error: FirestoreError) => void; complete?: () => void; } ): Unsubscribe; <AppModelType, DbModelType extends DocumentData>( query: Query<AppModelType, DbModelType>, options: SnapshotListenOptions, observer: { next?: (snapshot: QuerySnapshot<AppModelType, DbModelType>) => void; error?: (error: FirestoreError) => void; complete?: () => void; } ): Unsubscribe; <AppModelType, DbModelType extends DocumentData>( query: Query<AppModelType, DbModelType>, onNext: (snapshot: QuerySnapshot<AppModelType, DbModelType>) => void, onError?: (error: FirestoreError) => void, onCompletion?: () => void ): Unsubscribe; <AppModelType, DbModelType extends DocumentData>( query: Query<AppModelType, DbModelType>, options: SnapshotListenOptions, onNext: (snapshot: QuerySnapshot<AppModelType, DbModelType>) => void, onError?: (error: FirestoreError) => void, onCompletion?: () => void ): Unsubscribe;};
Attaches a listener for
DocumentSnapshot
events. You may either pass individualonNext
andonError
callbacks or pass a single observer object withnext
anderror
callbacks.NOTE: Although an
onCompletion
callback can be provided, it will never be called because the snapshot stream is never-ending.Parameter reference
A reference to the document to listen to.
Parameter observer
A single object containing
next
anderror
callbacks.Returns
An unsubscribe function that can be called to cancel the snapshot listener.
Attaches a listener for
DocumentSnapshot
events. You may either pass individualonNext
andonError
callbacks or pass a single observer object withnext
anderror
callbacks.NOTE: Although an
onCompletion
callback can be provided, it will never be called because the snapshot stream is never-ending.Parameter reference
A reference to the document to listen to.
Parameter options
Options controlling the listen behavior.
Parameter observer
A single object containing
next
anderror
callbacks.Returns
An unsubscribe function that can be called to cancel the snapshot listener.
Attaches a listener for
DocumentSnapshot
events. You may either pass individualonNext
andonError
callbacks or pass a single observer object withnext
anderror
callbacks.NOTE: Although an
onCompletion
callback can be provided, it will never be called because the snapshot stream is never-ending.Parameter reference
A reference to the document to listen to.
Parameter onNext
A callback to be called every time a new
DocumentSnapshot
is available.Parameter onError
A callback to be called if the listen fails or is cancelled. No further callbacks will occur.
Parameter onCompletion
Can be provided, but will not be called since streams are never ending.
Returns
An unsubscribe function that can be called to cancel the snapshot listener.
Attaches a listener for
DocumentSnapshot
events. You may either pass individualonNext
andonError
callbacks or pass a single observer object withnext
anderror
callbacks.NOTE: Although an
onCompletion
callback can be provided, it will never be called because the snapshot stream is never-ending.Parameter reference
A reference to the document to listen to.
Parameter options
Options controlling the listen behavior.
Parameter onNext
A callback to be called every time a new
DocumentSnapshot
is available.Parameter onError
A callback to be called if the listen fails or is cancelled. No further callbacks will occur.
Parameter onCompletion
Can be provided, but will not be called since streams are never ending.
Returns
An unsubscribe function that can be called to cancel the snapshot listener.
Attaches a listener for
QuerySnapshot
events. You may either pass individualonNext
andonError
callbacks or pass a single observer object withnext
anderror
callbacks. The listener can be cancelled by calling the function that is returned whenonSnapshot
is called.NOTE: Although an
onCompletion
callback can be provided, it will never be called because the snapshot stream is never-ending.Parameter query
The query to listen to.
Parameter observer
A single object containing
next
anderror
callbacks.Returns
An unsubscribe function that can be called to cancel the snapshot listener.
Attaches a listener for
QuerySnapshot
events. You may either pass individualonNext
andonError
callbacks or pass a single observer object withnext
anderror
callbacks. The listener can be cancelled by calling the function that is returned whenonSnapshot
is called.NOTE: Although an
onCompletion
callback can be provided, it will never be called because the snapshot stream is never-ending.Parameter query
The query to listen to.
Parameter options
Options controlling the listen behavior.
Parameter observer
A single object containing
next
anderror
callbacks.Returns
An unsubscribe function that can be called to cancel the snapshot listener.
Attaches a listener for
QuerySnapshot
events. You may either pass individualonNext
andonError
callbacks or pass a single observer object withnext
anderror
callbacks. The listener can be cancelled by calling the function that is returned whenonSnapshot
is called.NOTE: Although an
onCompletion
callback can be provided, it will never be called because the snapshot stream is never-ending.Parameter query
The query to listen to.
Parameter onNext
A callback to be called every time a new
QuerySnapshot
is available.Parameter onCompletion
Can be provided, but will not be called since streams are never ending.
Parameter onError
A callback to be called if the listen fails or is cancelled. No further callbacks will occur.
Returns
An unsubscribe function that can be called to cancel the snapshot listener.
Attaches a listener for
QuerySnapshot
events. You may either pass individualonNext
andonError
callbacks or pass a single observer object withnext
anderror
callbacks. The listener can be cancelled by calling the function that is returned whenonSnapshot
is called.NOTE: Although an
onCompletion
callback can be provided, it will never be called because the snapshot stream is never-ending.Parameter query
The query to listen to.
Parameter options
Options controlling the listen behavior.
Parameter onNext
A callback to be called every time a new
QuerySnapshot
is available.Parameter onCompletion
Can be provided, but will not be called since streams are never ending.
Parameter onError
A callback to be called if the listen fails or is cancelled. No further callbacks will occur.
Returns
An unsubscribe function that can be called to cancel the snapshot listener.
function onSnapshotsInSync
onSnapshotsInSync: { ( firestore: Firestore, observer: { next?: (value: void) => void; error?: (error: FirestoreError) => void; complete?: () => void; } ): Unsubscribe; (firestore: Firestore, onSync: () => void): Unsubscribe;};
Attaches a listener for a snapshots-in-sync event. The snapshots-in-sync event 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 sync with each other, but does not relate to whether those snapshots are in sync with the server. Use SnapshotMetadata in the individual listeners to determine if a snapshot is from the cache or the server.
Parameter firestore
The instance of Firestore for synchronizing snapshots.
Parameter observer
A single object containing
next
anderror
callbacks.Returns
An unsubscribe function that can be called to cancel the snapshot listener.
Attaches a listener for a snapshots-in-sync event. The snapshots-in-sync event 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 sync with each other, but does not relate to whether those snapshots are in sync with the server. Use
SnapshotMetadata
in the individual listeners to determine if a snapshot is from the cache or the server.Parameter firestore
The
Firestore
instance for synchronizing snapshots.Parameter onSync
A callback to be called every time all snapshot listeners are in sync with each other.
Returns
An unsubscribe function that can be called to cancel the snapshot listener.
function or
or: ( ...queryConstraints: QueryFilterConstraint[]) => QueryCompositeFilterConstraint;
Creates a new QueryCompositeFilterConstraint that is a disjunction of the given filter constraints. A disjunction filter includes a document if it satisfies any of the given filters.
Parameter queryConstraints
Optional. The list of QueryFilterConstraints to perform a disjunction for. These must be created with calls to where, or, or and.
Returns
The newly created QueryCompositeFilterConstraint.
function orderBy
orderBy: ( fieldPath: string | FieldPath, directionStr?: OrderByDirection) => QueryOrderByConstraint;
Creates a QueryOrderByConstraint that sorts the query result by the specified field, optionally in descending order instead of ascending.
Note: Documents that do not contain the specified field will not be present in the query result.
Parameter fieldPath
The field to sort by.
Parameter directionStr
Optional direction to sort by ('asc' or 'desc'). If not specified, order will be ascending.
Returns
The created QueryOrderByConstraint.
function persistentLocalCache
persistentLocalCache: ( settings?: PersistentCacheSettings) => PersistentLocalCache;
Creates an instance of
PersistentLocalCache
. The instance can be set toFirestoreSettings.cache
to tell the SDK which cache layer to use.Persistent cache cannot be used in a Node.js environment.
function persistentMultipleTabManager
persistentMultipleTabManager: () => PersistentMultipleTabManager;
Creates an instance of
PersistentMultipleTabManager
.
function persistentSingleTabManager
persistentSingleTabManager: ( settings: PersistentSingleTabManagerSettings | undefined) => PersistentSingleTabManager;
Creates an instance of
PersistentSingleTabManager
.Parameter settings
Configures the created tab manager.
function query
query: { <AppModelType, DbModelType extends DocumentData>( query: Query<AppModelType, DbModelType>, compositeFilter: QueryCompositeFilterConstraint, ...queryConstraints: QueryNonFilterConstraint[] ): Query<AppModelType, DbModelType>; <AppModelType, DbModelType extends DocumentData>( query: Query<AppModelType, DbModelType>, ...queryConstraints: QueryConstraint[] ): Query<AppModelType, DbModelType>;};
Creates a new immutable instance of Query that is extended to also include additional query constraints.
Parameter query
The Query instance to use as a base for the new constraints.
Parameter compositeFilter
The QueryCompositeFilterConstraint to apply. Create QueryCompositeFilterConstraint using and or or.
Parameter queryConstraints
Additional QueryNonFilterConstraints to apply (e.g. orderBy, limit).
Throws
if any of the provided query constraints cannot be combined with the existing or new constraints.
Creates a new immutable instance of Query that is extended to also include additional query constraints.
Parameter query
The Query instance to use as a base for the new constraints.
Parameter queryConstraints
The list of QueryConstraints to apply.
Throws
if any of the provided query constraints cannot be combined with the existing or new constraints.
function queryEqual
queryEqual: <AppModelType, DbModelType extends DocumentData>( left: Query<AppModelType, DbModelType>, right: Query<AppModelType, DbModelType>) => boolean;
Returns true if the provided queries point to the same collection and apply the same constraints.
Parameter left
A
Query
to compare.Parameter right
A
Query
to compare.Returns
true if the references point to the same location in the same Firestore database.
function refEqual
refEqual: <AppModelType, DbModelType extends DocumentData>( left: | DocumentReference<AppModelType, DbModelType> | CollectionReference<AppModelType, DbModelType>, right: | DocumentReference<AppModelType, DbModelType> | CollectionReference<AppModelType, DbModelType>) => boolean;
Returns true if the provided references are equal.
Parameter left
A reference to compare.
Parameter right
A reference to compare.
Returns
true if the references point to the same location in the same Firestore database.
function runTransaction
runTransaction: <T>( firestore: Firestore, updateFunction: (transaction: Transaction) => Promise<T>, options?: TransactionOptions) => Promise<T>;
Executes the given
updateFunction
and then attempts to commit the changes applied within the transaction. If any document read within the transaction has changed, Cloud Firestore retries theupdateFunction
. If it fails to commit after 5 attempts, the transaction fails.The maximum number of writes allowed in a single transaction is 500.
Parameter firestore
A reference to the Firestore database to run this transaction against.
Parameter updateFunction
The function to execute within the transaction context.
Parameter options
An options object to configure maximum number of attempts to commit.
Returns
If the transaction completed successfully or was explicitly aborted (the
updateFunction
returned a failed promise), the promise returned by theupdateFunction
is returned here. Otherwise, if the transaction failed, a rejected promise with the corresponding failure error is returned.
function serverTimestamp
serverTimestamp: () => FieldValue;
Returns a sentinel used with @firebase/firestore#setDoc or @firebase/firestore#updateDoc to include a server-generated timestamp in the written data.
function setDoc
setDoc: { <AppModelType, DbModelType extends DocumentData>( reference: DocumentReference<AppModelType, DbModelType>, data: WithFieldValue<AppModelType> ): Promise<void>; <AppModelType, DbModelType extends DocumentData>( reference: DocumentReference<AppModelType, DbModelType>, data: PartialWithFieldValue<AppModelType>, options: SetOptions ): Promise<void>;};
Writes to the document referred to by this
DocumentReference
. If the document does not yet exist, it will be created.Parameter reference
A reference to the document to write.
Parameter data
A map of the fields and values for the document.
Returns
A
Promise
resolved once the data has been successfully written to the backend (note that it won't resolve while you're offline).Writes to the document referred to by the specified
DocumentReference
. If the document does not yet exist, it will be created. If you providemerge
ormergeFields
, the provided data can be merged into an existing document.Parameter reference
A reference to the document to write.
Parameter data
A map of the fields and values for the document.
Parameter options
An object to configure the set behavior.
Returns
A Promise resolved once the data has been successfully written to the backend (note that it won't resolve while you're offline).
function setIndexConfiguration
setIndexConfiguration: { (firestore: Firestore, configuration: IndexConfiguration): Promise<void>; (firestore: Firestore, json: string): Promise<void>;};
Configures indexing for local query execution. Any previous index configuration is overridden. The
Promise
resolves once the index configuration has been persisted.The index entries themselves are created asynchronously. You can continue to use queries that require indexing even if the indices are not yet available. Query execution will automatically start using the index once the index entries have been written.
Indexes are only supported with IndexedDb persistence. If IndexedDb is not enabled, any index configuration is ignored.
Parameter firestore
The Firestore instance to configure indexes for.
Parameter configuration
The index definition.
Returns
A
Promise
that resolves once all indices are successfully configured.Throws
FirestoreError if the JSON format is invalid.
Modifiers
@beta
Deprecated
Instead of creating cache indexes manually, consider using
enablePersistentCacheIndexAutoCreation()
to let the SDK decide whether to create cache indexes for queries running locally.Configures indexing for local query execution. Any previous index configuration is overridden. The
Promise
resolves once the index configuration has been persisted.The index entries themselves are created asynchronously. You can continue to use queries that require indexing even if the indices are not yet available. Query execution will automatically start using the index once the index entries have been written.
Indexes are only supported with IndexedDb persistence. Invoke either
enableIndexedDbPersistence()
orenableMultiTabIndexedDbPersistence()
before setting an index configuration. If IndexedDb is not enabled, any index configuration is ignored.The method accepts the JSON format exported by the Firebase CLI (`firebase firestore:indexes`). If the JSON format is invalid, this method throws an error.
Parameter firestore
The Firestore instance to configure indexes for.
Parameter json
The JSON format exported by the Firebase CLI.
Returns
A
Promise
that resolves once all indices are successfully configured.Throws
FirestoreError if the JSON format is invalid.
Modifiers
@beta
Deprecated
Instead of creating cache indexes manually, consider using
enablePersistentCacheIndexAutoCreation()
to let the SDK decide whether to create cache indexes for queries running locally.
function setLogLevel
setLogLevel: (logLevel: LogLevel) => void;
Sets the verbosity of Cloud Firestore logs (debug, error, or silent).
Parameter logLevel
The verbosity you set for activity and error logging. Can be any of the following values:
debug
for the most verbose logging level, primarily for debugging.error
to log errors only.silent
to turn off logging.
function snapshotEqual
snapshotEqual: <AppModelType, DbModelType extends DocumentData>( left: | DocumentSnapshot<AppModelType, DbModelType> | QuerySnapshot<AppModelType, DbModelType>, right: | DocumentSnapshot<AppModelType, DbModelType> | QuerySnapshot<AppModelType, DbModelType>) => boolean;
Returns true if the provided snapshots are equal.
Parameter left
A snapshot to compare.
Parameter right
A snapshot to compare.
Returns
true if the snapshots are equal.
function startAfter
startAfter: { <AppModelType, DbModelType extends DocumentData>( snapshot: DocumentSnapshot<AppModelType, DbModelType> ): QueryStartAtConstraint; (...fieldValues: unknown[]): QueryStartAtConstraint;};
Creates a QueryStartAtConstraint that modifies the result set to start after the provided document (exclusive). The starting position is relative to the order of the query. The document must contain all of the fields provided in the orderBy of the query.
Parameter snapshot
The snapshot of the document to start after.
Returns
A QueryStartAtConstraint to pass to
query()
Creates a QueryStartAtConstraint that modifies the result set to start after the provided fields relative to the order of the query. The order of the field values must match the order of the order by clauses of the query.
Parameter fieldValues
The field values to start this query after, in order of the query's order by.
Returns
A QueryStartAtConstraint to pass to
query()
function startAt
startAt: { <AppModelType, DbModelType extends DocumentData>( snapshot: DocumentSnapshot<AppModelType, DbModelType> ): QueryStartAtConstraint; (...fieldValues: unknown[]): QueryStartAtConstraint;};
Creates a QueryStartAtConstraint that modifies the result set to start at the provided document (inclusive). The starting position is relative to the order of the query. The document must contain all of the fields provided in the
orderBy
of this query.Parameter snapshot
The snapshot of the document to start at.
Returns
A QueryStartAtConstraint to pass to
query()
.Creates a QueryStartAtConstraint that modifies the result set to start at the provided fields relative to the order of the query. The order of the field values must match the order of the order by clauses of the query.
Parameter fieldValues
The field values to start this query at, in order of the query's order by.
Returns
A QueryStartAtConstraint to pass to
query()
.
function sum
sum: (field: string | FieldPath) => AggregateField<number>;
Create an AggregateField object that can be used to compute the sum of a specified field over a range of documents in the result set of a query.
Parameter field
Specifies the field to sum across the result set.
function terminate
terminate: (firestore: Firestore) => Promise<void>;
Terminates the provided Firestore instance.
After calling
terminate()
only theclearIndexedDbPersistence()
function may be used. Any other function will throw aFirestoreError
.To restart after termination, create a new instance of FirebaseFirestore with getFirestore.
Termination does not cancel any pending writes, and any promises that are awaiting a response from the server will not be resolved. If you have persistence enabled, the next time you start this instance, it will resume sending these writes to the server.
Note: Under normal circumstances, calling
terminate()
is not required. This function is useful only when you want to force this instance to release all of its resources or in combination withclearIndexedDbPersistence()
to ensure that all local state is destroyed between test runs.Returns
A
Promise
that is resolved when the instance has been successfully terminated.
function updateDoc
updateDoc: { <AppModelType, DbModelType extends DocumentData>( reference: DocumentReference<AppModelType, DbModelType>, data: UpdateData<DbModelType> ): Promise<void>; <AppModelType, DbModelType extends DocumentData>( reference: DocumentReference<AppModelType, DbModelType>, field: string | FieldPath, value: unknown, ...moreFieldsAndValues: unknown[] ): Promise<void>;};
Updates fields in the document referred to by the specified
DocumentReference
. The update will fail if applied to a document that does not exist.Parameter reference
A reference to the document to update.
Parameter data
An object containing the fields and values with which to update the document. Fields can contain dots to reference nested fields within the document.
Returns
A
Promise
resolved once the data has been successfully written to the backend (note that it won't resolve while you're offline).Updates fields in the document referred to by the specified
DocumentReference
The update will fail if applied to a document that does not exist.Nested fields can be updated by providing dot-separated field path strings or by providing
FieldPath
objects.Parameter reference
A reference to the document to update.
Parameter field
The first field to update.
Parameter value
The first value.
Parameter moreFieldsAndValues
Additional key value pairs.
Returns
A
Promise
resolved once the data has been successfully written to the backend (note that it won't resolve while you're offline).
function vector
vector: (values?: number[]) => VectorValue;
Creates a new
VectorValue
constructed with a copy of the given array of numbers.Parameter values
Create a
VectorValue
instance with a copy of this array of numbers.Returns
A new
VectorValue
constructed with a copy of the given array of numbers.
function waitForPendingWrites
waitForPendingWrites: (firestore: Firestore) => Promise<void>;
Waits until all currently pending writes for the active user have been acknowledged by the backend.
The returned promise resolves immediately if there are no outstanding writes. Otherwise, the promise waits for all previously issued writes (including those written in a previous app session), but it does not wait for writes that were added after the function is called. If you want to wait for additional writes, call
waitForPendingWrites()
again.Any outstanding
waitForPendingWrites()
promises are rejected during user changes.Returns
A
Promise
which resolves when all currently pending writes have been acknowledged by the backend.
function where
where: ( fieldPath: string | FieldPath, opStr: WhereFilterOp, value: unknown) => QueryFieldFilterConstraint;
Creates a QueryFieldFilterConstraint that enforces that documents must contain the specified field and that the value should satisfy the relation constraint provided.
Parameter fieldPath
The path to compare
Parameter opStr
The operation string (e.g "<", "<=", "==", "<", "<=", "!=").
Parameter value
The value for comparison
Returns
The created QueryFieldFilterConstraint.
function writeBatch
writeBatch: (firestore: Firestore) => WriteBatch;
Creates a write batch, used for performing multiple writes as a single atomic operation. The maximum number of writes allowed in a single WriteBatch is 500.
Unlike transactions, write batches are persisted offline and therefore are preferable when you don't need to condition your writes on read data.
Returns
A WriteBatch that can be used to atomically execute multiple writes.
Classes
class AggregateField
class AggregateField<T> {}
Represents an aggregation that can be performed by Firestore.
property aggregateType
readonly aggregateType: AggregateType;
Indicates the aggregation operation of this AggregateField.
property type
readonly type: string;
A type string to uniquely identify instances of this class.
class AggregateQuerySnapshot
class AggregateQuerySnapshot< AggregateSpecType extends AggregateSpec, AppModelType = DocumentData, DbModelType extends DocumentData = DocumentData> {}
The results of executing an aggregation query.
property query
readonly query: Query<AppModelType, DbModelType>;
The underlying query over which the aggregations recorded in this
AggregateQuerySnapshot
were performed.
property type
readonly type: string;
A type string to uniquely identify instances of this class.
method data
data: () => AggregateSpecData<AggregateSpecType>;
Returns the results of the aggregations performed over the underlying query.
The keys of the returned object will be the same as those of the
AggregateSpec
object specified to the aggregation method, and the values will be the corresponding aggregation result.Returns
The results of the aggregations performed over the underlying query.
class Bytes
class Bytes {}
An immutable object representing an array of bytes.
method fromBase64String
static fromBase64String: (base64: string) => Bytes;
Creates a new
Bytes
object from the given Base64 string, converting it to bytes.Parameter base64
The Base64 string used to create the
Bytes
object.
method fromUint8Array
static fromUint8Array: (array: Uint8Array) => Bytes;
Creates a new
Bytes
object from the given Uint8Array.Parameter array
The Uint8Array used to create the
Bytes
object.
method isEqual
isEqual: (other: Bytes) => boolean;
Returns true if this
Bytes
object is equal to the provided one.Parameter other
The
Bytes
object to compare against.Returns
true if this
Bytes
object is equal to the provided one.
method toBase64
toBase64: () => string;
Returns the underlying bytes as a Base64-encoded string.
Returns
The Base64-encoded string created from the
Bytes
object.
method toString
toString: () => string;
Returns a string representation of the
Bytes
object.Returns
A string representation of the
Bytes
object.
method toUint8Array
toUint8Array: () => Uint8Array;
Returns the underlying bytes in a new
Uint8Array
.Returns
The Uint8Array created from the
Bytes
object.
class CollectionReference
class CollectionReference< AppModelType = DocumentData, DbModelType extends DocumentData = DocumentData> extends Query<AppModelType, DbModelType> {}
A
CollectionReference
object can be used for adding documents, getting document references, and querying for documents (using query).
property id
readonly id: string;
The collection's identifier.
property parent
readonly parent: DocumentReference<DocumentData, DocumentData>;
A reference to the containing
DocumentReference
if this is a subcollection. If this isn't a subcollection, the reference is null.
property path
readonly path: string;
A string representing the path of the referenced collection (relative to the root of the database).
property type
readonly type: string;
The type of this Firestore reference.
method withConverter
withConverter: { <NewAppModelType, NewDbModelType extends DocumentData = DocumentData>( converter: FirestoreDataConverter<NewAppModelType, NewDbModelType> ): CollectionReference<NewAppModelType, NewDbModelType>; (converter: null): CollectionReference<DocumentData, DocumentData>;};
Applies a custom data converter to this
CollectionReference
, allowing you to use your own custom model objects with Firestore. When you call addDoc with the returnedCollectionReference
instance, the provided converter will convert between Firestore data of typeNewDbModelType
and your custom typeNewAppModelType
.Parameter converter
Converts objects to and from Firestore.
Returns
A
CollectionReference
that uses the provided converter.Removes the current converter.
Parameter converter
null
removes the current converter.Returns
A
CollectionReference<DocumentData, DocumentData>
that does not use a converter.
class DocumentReference
class DocumentReference< AppModelType = DocumentData, DbModelType extends DocumentData = DocumentData> {}
A
DocumentReference
refers to a document location in a Firestore database and can be used to write, read, or listen to the location. The document at the referenced location may or may not exist.
property converter
readonly converter: FirestoreDataConverter<AppModelType, DbModelType>;
If provided, the
FirestoreDataConverter
associated with this instance.
property firestore
readonly firestore: Firestore;
The Firestore instance the document is in. This is useful for performing transactions, for example.
property id
readonly id: string;
The document's identifier within its collection.
property parent
readonly parent: CollectionReference<AppModelType, DbModelType>;
The collection this
DocumentReference
belongs to.
property path
readonly path: string;
A string representing the path of the referenced document (relative to the root of the database).
property type
readonly type: string;
The type of this Firestore reference.
method withConverter
withConverter: { <NewAppModelType, NewDbModelType extends DocumentData = DocumentData>( converter: FirestoreDataConverter<NewAppModelType, NewDbModelType> ): DocumentReference<NewAppModelType, NewDbModelType>; (converter: null): DocumentReference<DocumentData, DocumentData>;};
Applies a custom data converter to this
DocumentReference
, allowing you to use your own custom model objects with Firestore. When you call @firebase/firestore#setDoc, @firebase/firestore#getDoc, etc. with the returnedDocumentReference
instance, the provided converter will convert between Firestore data of typeNewDbModelType
and your custom typeNewAppModelType
.Parameter converter
Converts objects to and from Firestore.
Returns
A
DocumentReference
that uses the provided converter.Removes the current converter.
Parameter converter
null
removes the current converter.Returns
A
DocumentReference<DocumentData, DocumentData>
that does not use a converter.
class DocumentSnapshot
class DocumentSnapshot< AppModelType = DocumentData, DbModelType extends DocumentData = DocumentData> {}
A
DocumentSnapshot
contains data read from a document in your Firestore database. The data can be extracted with.data()
or.get(<field>)
to get a specific field.For a
DocumentSnapshot
that points to a non-existing document, any data access will return 'undefined'. You can use theexists()
method to explicitly verify a document's existence.
constructor
protected constructor();
property id
readonly id: string;
Property of the
DocumentSnapshot
that provides the document's ID.
property metadata
readonly metadata: SnapshotMetadata;
Metadata about the
DocumentSnapshot
, including information about its source and local modifications.
property ref
readonly ref: DocumentReference<AppModelType, DbModelType>;
The
DocumentReference
for the document included in theDocumentSnapshot
.
method data
data: (options?: SnapshotOptions) => AppModelType | undefined;
Retrieves all fields in the document as an
Object
. Returnsundefined
if the document doesn't exist.By default,
serverTimestamp()
values that have not yet been set to their final value will be returned asnull
. You can override this by passing an options object.Parameter options
An options object to configure how data is retrieved from the snapshot (for example the desired behavior for server timestamps that have not yet been set to their final value).
Returns
An
Object
containing all fields in the document orundefined
if the document doesn't exist.
method exists
exists: () => this is QueryDocumentSnapshot<AppModelType, DbModelType>;
Returns whether or not the data exists. True if the document exists.
method get
get: (fieldPath: string | FieldPath, options?: SnapshotOptions) => any;
Retrieves the field specified by
fieldPath
. Returnsundefined
if the document or field doesn't exist.By default, a
serverTimestamp()
that has not yet been set to its final value will be returned asnull
. You can override this by passing an options object.Parameter fieldPath
The path (for example 'foo' or 'foo.bar') to a specific field.
Parameter options
An options object to configure how the field is retrieved from the snapshot (for example the desired behavior for server timestamps that have not yet been set to their final value).
Returns
The data at the specified field location or undefined if no such field exists in the document.
class FieldPath
class FieldPath {}
A
FieldPath
refers to a field in a document. The path may consist of a single field name (referring to a top-level field in the document), or a list of field names (referring to a nested field in the document).Create a
FieldPath
by providing field names. If more than one field name is provided, the path will point to a nested field in a document.
constructor
constructor(...fieldNames: string[]);
Creates a
FieldPath
from the provided field names. If more than one field name is provided, the path will point to a nested field in a document.Parameter fieldNames
A list of field names.
method isEqual
isEqual: (other: FieldPath) => boolean;
Returns true if this
FieldPath
is equal to the provided one.Parameter other
The
FieldPath
to compare against.Returns
true if this
FieldPath
is equal to the provided one.
class FieldValue
abstract class FieldValue {}
Sentinel values that can be used when writing document fields with
set()
orupdate()
.
method isEqual
abstract isEqual: (other: FieldValue) => boolean;
Compares
FieldValue
s for equality.
class Firestore
class Firestore {}
The Cloud Firestore service interface.
Do not call this constructor directly. Instead, use getFirestore.
property app
readonly app: FirebaseApp;
The @firebase/app#FirebaseApp associated with this
Firestore
service instance.
property type
type: 'firestore-lite' | 'firestore';
Whether it's a Firestore or Firestore Lite instance.
method toJSON
toJSON: () => object;
Returns a JSON-serializable representation of this
Firestore
instance.
class FirestoreError
class FirestoreError extends FirebaseError {}
An error returned by a Firestore operation.
class GeoPoint
class GeoPoint {}
An immutable object representing a geographic location in Firestore. The location is represented as latitude/longitude pair.
Latitude values are in the range of [-90, 90]. Longitude values are in the range of [-180, 180].
constructor
constructor(latitude: number, longitude: number);
Creates a new immutable
GeoPoint
object with the provided latitude and longitude values.Parameter latitude
The latitude as number between -90 and 90.
Parameter longitude
The longitude as number between -180 and 180.
property latitude
readonly latitude: number;
The latitude of this
GeoPoint
instance.
property longitude
readonly longitude: number;
The longitude of this
GeoPoint
instance.
method isEqual
isEqual: (other: GeoPoint) => boolean;
Returns true if this
GeoPoint
is equal to the provided one.Parameter other
The
GeoPoint
to compare against.Returns
true if this
GeoPoint
is equal to the provided one.
method toJSON
toJSON: () => { latitude: number; longitude: number };
Returns a JSON-serializable representation of this GeoPoint.
class LoadBundleTask
class LoadBundleTask implements PromiseLike<LoadBundleTaskProgress> {}
Represents the task of loading a Firestore bundle. It provides progress of bundle loading, as well as task completion and error events.
The API is compatible with
Promise<LoadBundleTaskProgress>
.
method catch
catch: <R>( onRejected: (a: Error) => R | PromiseLike<R>) => Promise<R | LoadBundleTaskProgress>;
Implements the
Promise<LoadBundleTaskProgress>.catch
interface.Parameter onRejected
Called when an error occurs during bundle loading.
method onProgress
onProgress: ( next?: (progress: LoadBundleTaskProgress) => unknown, error?: (err: Error) => unknown, complete?: () => void) => void;
Registers functions to listen to bundle loading progress events.
Parameter next
Called when there is a progress update from bundle loading. Typically
next
calls occur each time a Firestore document is loaded from the bundle.Parameter error
Called when an error occurs during bundle loading. The task aborts after reporting the error, and there should be no more updates after this.
Parameter complete
Called when the loading task is complete.
method then
then: <T, R>( onFulfilled?: (a: LoadBundleTaskProgress) => T | PromiseLike<T>, onRejected?: (a: Error) => R | PromiseLike<R>) => Promise<T | R>;
Implements the
Promise<LoadBundleTaskProgress>.then
interface.Parameter onFulfilled
Called on the completion of the loading task with a final
LoadBundleTaskProgress
update. The update will always have itstaskState
set to"Success"
.Parameter onRejected
Called when an error occurs during bundle loading.
class PersistentCacheIndexManager
class PersistentCacheIndexManager {}
A
PersistentCacheIndexManager
for configuring persistent cache indexes used for local query execution.To use, call
getPersistentCacheIndexManager()
to get an instance.
property type
readonly type: string;
A type string to uniquely identify instances of this class.
class Query
class Query< AppModelType = DocumentData, DbModelType extends DocumentData = DocumentData> {}
A
Query
refers to a query which you can read or listen to. You can also construct refinedQuery
objects by adding filters and ordering.
constructor
protected constructor();
property converter
readonly converter: FirestoreDataConverter<AppModelType, DbModelType>;
If provided, the
FirestoreDataConverter
associated with this instance.
property firestore
readonly firestore: Firestore;
The
Firestore
instance for the Firestore database (useful for performing transactions, etc.).
property type
readonly type: 'collection' | 'query';
The type of this Firestore reference.
method withConverter
withConverter: { (converter: null): Query<DocumentData, DocumentData>; <NewAppModelType, NewDbModelType extends DocumentData = DocumentData>( converter: FirestoreDataConverter<NewAppModelType, NewDbModelType> ): Query<NewAppModelType, NewDbModelType>;};
Removes the current converter.
Parameter converter
null
removes the current converter.Returns
A
Query<DocumentData, DocumentData>
that does not use a converter.Applies a custom data converter to this query, allowing you to use your own custom model objects with Firestore. When you call getDocs with the returned query, the provided converter will convert between Firestore data of type
NewDbModelType
and your custom typeNewAppModelType
.Parameter converter
Converts objects to and from Firestore.
Returns
A
Query
that uses the provided converter.
class QueryCompositeFilterConstraint
class QueryCompositeFilterConstraint {}
A
QueryCompositeFilterConstraint
is used to narrow the set of documents returned by a Firestore query by performing the logical OR or AND of multiple QueryFieldFilterConstraints or QueryCompositeFilterConstraints.QueryCompositeFilterConstraint
s are created by invoking or or and and can then be passed to query to create a new query instance that also contains theQueryCompositeFilterConstraint
.
property type
readonly type: 'or' | 'and';
The type of this query constraint
class QueryConstraint
abstract class QueryConstraint {}
A
QueryConstraint
is used to narrow the set of documents returned by a Firestore query.QueryConstraint
s are created by invoking where, orderBy, startAt, startAfter, endBefore, endAt, limit, limitToLast and can then be passed to query to create a new query instance that also contains thisQueryConstraint
.
property type
abstract readonly type: QueryConstraintType;
The type of this query constraint
class QueryDocumentSnapshot
class QueryDocumentSnapshot< AppModelType = DocumentData, DbModelType extends DocumentData = DocumentData> extends DocumentSnapshot<AppModelType, DbModelType> {}
A
QueryDocumentSnapshot
contains data read from a document in your Firestore database as part of a query. The document is guaranteed to exist and its data can be extracted with.data()
or.get(<field>)
to get a specific field.A
QueryDocumentSnapshot
offers the same API surface as aDocumentSnapshot
. Since query results contain only existing documents, theexists
property will always be true anddata()
will never return 'undefined'.
method data
data: (options?: SnapshotOptions) => AppModelType;
Retrieves all fields in the document as an
Object
.By default,
serverTimestamp()
values that have not yet been set to their final value will be returned asnull
. You can override this by passing an options object.Parameter options
An options object to configure how data is retrieved from the snapshot (for example the desired behavior for server timestamps that have not yet been set to their final value).
Returns
An
Object
containing all fields in the document.Modifiers
@override
class QueryEndAtConstraint
class QueryEndAtConstraint extends QueryConstraint {}
property type
readonly type: 'endAt' | 'endBefore';
The type of this query constraint
class QueryFieldFilterConstraint
class QueryFieldFilterConstraint extends QueryConstraint {}
A
QueryFieldFilterConstraint
is used to narrow the set of documents returned by a Firestore query by filtering on one or more document fields.QueryFieldFilterConstraint
s are created by invoking where and can then be passed to query to create a new query instance that also contains thisQueryFieldFilterConstraint
.
property type
readonly type: string;
The type of this query constraint
class QueryLimitConstraint
class QueryLimitConstraint extends QueryConstraint {}
A
QueryLimitConstraint
is used to limit the number of documents returned by a Firestore query.QueryLimitConstraint
s are created by invoking limit or limitToLast and can then be passed to query to create a new query instance that also contains thisQueryLimitConstraint
.
property type
readonly type: 'limit' | 'limitToLast';
The type of this query constraint
class QueryOrderByConstraint
class QueryOrderByConstraint extends QueryConstraint {}
A
QueryOrderByConstraint
is used to sort the set of documents returned by a Firestore query.QueryOrderByConstraint
s are created by invoking orderBy and can then be passed to query to create a new query instance that also contains thisQueryOrderByConstraint
.Note: Documents that do not contain the orderBy field will not be present in the query result.
property type
readonly type: string;
The type of this query constraint
class QuerySnapshot
class QuerySnapshot< AppModelType = DocumentData, DbModelType extends DocumentData = DocumentData> {}
A
QuerySnapshot
contains zero or moreDocumentSnapshot
objects representing the results of a query. The documents can be accessed as an array via thedocs
property or enumerated using theforEach
method. The number of documents can be determined via theempty
andsize
properties.
property docs
readonly docs: QueryDocumentSnapshot<AppModelType, DbModelType>[];
An array of all the documents in the
QuerySnapshot
.
property empty
readonly empty: boolean;
True if there are no documents in the
QuerySnapshot
.
property metadata
readonly metadata: SnapshotMetadata;
Metadata about this snapshot, concerning its source and if it has local modifications.
property query
readonly query: Query<AppModelType, DbModelType>;
The query on which you called
get
oronSnapshot
in order to get thisQuerySnapshot
.
property size
readonly size: number;
The number of documents in the
QuerySnapshot
.
method docChanges
docChanges: ( options?: SnapshotListenOptions) => Array<DocumentChange<AppModelType, DbModelType>>;
Returns an array of the documents changes since the last snapshot. If this is the first snapshot, all documents will be in the list as 'added' changes.
Parameter options
SnapshotListenOptions
that control whether metadata-only changes (i.e. onlyDocumentSnapshot.metadata
changed) should trigger snapshot events.
method forEach
forEach: ( callback: (result: QueryDocumentSnapshot<AppModelType, DbModelType>) => void, thisArg?: unknown) => void;
Enumerates all of the documents in the
QuerySnapshot
.Parameter callback
A callback to be called with a
QueryDocumentSnapshot
for each document in the snapshot.Parameter thisArg
The
this
binding for the callback.
class QueryStartAtConstraint
class QueryStartAtConstraint extends QueryConstraint {}
A
QueryStartAtConstraint
is used to exclude documents from the start of a result set returned by a Firestore query.QueryStartAtConstraint
s are created by invoking startAt or startAfter and can then be passed to query to create a new query instance that also contains thisQueryStartAtConstraint
.
property type
readonly type: 'startAt' | 'startAfter';
The type of this query constraint
class SnapshotMetadata
class SnapshotMetadata {}
Metadata about a snapshot, describing the state of the snapshot.
property fromCache
readonly fromCache: boolean;
True if the snapshot was created from cached data rather than guaranteed up-to-date server data. If your listener has opted into metadata updates (via
SnapshotListenOptions
) you will receive another snapshot withfromCache
set to false once the client has received up-to-date data from the backend.
property hasPendingWrites
readonly hasPendingWrites: boolean;
True if the snapshot contains the result of local writes (for example
set()
orupdate()
calls) that have not yet been committed to the backend. If your listener has opted into metadata updates (viaSnapshotListenOptions
) you will receive another snapshot withhasPendingWrites
equal to false once the writes have been committed to the backend.
method isEqual
isEqual: (other: SnapshotMetadata) => boolean;
Returns true if this
SnapshotMetadata
is equal to the provided one.Parameter other
The
SnapshotMetadata
to compare against.Returns
true if this
SnapshotMetadata
is equal to the provided one.
class Timestamp
class Timestamp {}
A
Timestamp
represents a point in time independent of any time zone or calendar, represented as seconds and fractions of seconds at nanosecond resolution in UTC Epoch time.It is encoded using the Proleptic Gregorian Calendar which extends the Gregorian calendar backwards to year one. It is encoded assuming all minutes are 60 seconds long, i.e. leap seconds are "smeared" so that no leap second table is needed for interpretation. Range is from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59.999999999Z.
For examples and further specifications, refer to the Timestamp definition.
constructor
constructor(seconds: number, nanoseconds: number);
Creates a new timestamp.
Parameter seconds
The number of seconds of UTC time since Unix epoch 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive.
Parameter nanoseconds
The non-negative fractions of a second at nanosecond resolution. Negative second values with fractions must still have non-negative nanoseconds values that count forward in time. Must be from 0 to 999,999,999 inclusive.
property nanoseconds
readonly nanoseconds: number;
The fractions of a second at nanosecond resolution.*
property seconds
readonly seconds: number;
The number of seconds of UTC time since Unix epoch 1970-01-01T00:00:00Z.
method fromDate
static fromDate: (date: Date) => Timestamp;
Creates a new timestamp from the given date.
Parameter date
The date to initialize the
Timestamp
from.Returns
A new
Timestamp
representing the same point in time as the given date.
method fromMillis
static fromMillis: (milliseconds: number) => Timestamp;
Creates a new timestamp from the given number of milliseconds.
Parameter milliseconds
Number of milliseconds since Unix epoch 1970-01-01T00:00:00Z.
Returns
A new
Timestamp
representing the same point in time as the given number of milliseconds.
method isEqual
isEqual: (other: Timestamp) => boolean;
Returns true if this
Timestamp
is equal to the provided one.Parameter other
The
Timestamp
to compare against.Returns
true if this
Timestamp
is equal to the provided one.
method now
static now: () => Timestamp;
Creates a new timestamp with the current date, with millisecond precision.
Returns
a new timestamp representing the current date.
method toDate
toDate: () => Date;
Converts a
Timestamp
to a JavaScriptDate
object. This conversion causes a loss of precision sinceDate
objects only support millisecond precision.Returns
JavaScript
Date
object representing the same point in time as thisTimestamp
, with millisecond precision.
method toJSON
toJSON: () => { seconds: number; nanoseconds: number };
Returns a JSON-serializable representation of this
Timestamp
.
method toMillis
toMillis: () => number;
Converts a
Timestamp
to a numeric timestamp (in milliseconds since epoch). This operation causes a loss of precision.Returns
The point in time corresponding to this timestamp, represented as the number of milliseconds since Unix epoch 1970-01-01T00:00:00Z.
method toString
toString: () => string;
Returns a textual representation of this
Timestamp
.
method valueOf
valueOf: () => string;
Converts this object to a primitive string, which allows
Timestamp
objects to be compared using the>
,<=
,>=
and>
operators.
class Transaction
class Transaction {}
A reference to a transaction.
The
Transaction
object passed to a transaction'supdateFunction
provides the methods to read and write data within the transaction context. See runTransaction.
method delete
delete: <AppModelType, DbModelType extends DocumentData>( documentRef: DocumentReference<AppModelType, DbModelType>) => this;
Deletes the document referred to by the provided DocumentReference.
Parameter documentRef
A reference to the document to be deleted.
Returns
This
Transaction
instance. Used for chaining method calls.
method get
get: <AppModelType, DbModelType extends DocumentData>( documentRef: DocumentReference<AppModelType, DbModelType>) => Promise<DocumentSnapshot<AppModelType, DbModelType>>;
Reads the document referenced by the provided DocumentReference.
Parameter documentRef
A reference to the document to be read.
Returns
A
DocumentSnapshot
with the read data.
method set
set: { <AppModelType, DbModelType extends DocumentData>( documentRef: DocumentReference<AppModelType, DbModelType>, data: WithFieldValue<AppModelType> ): this; <AppModelType, DbModelType extends DocumentData>( documentRef: DocumentReference<AppModelType, DbModelType>, data: PartialWithFieldValue<AppModelType>, options: SetOptions ): this;};
Writes to the document referred to by the provided DocumentReference. If the document does not exist yet, it will be created.
Parameter documentRef
A reference to the document to be set.
Parameter data
An object of the fields and values for the document.
Returns
This
Transaction
instance. Used for chaining method calls.Throws
Error - If the provided input is not a valid Firestore document.
Writes to the document referred to by the provided DocumentReference. If the document does not exist yet, it will be created. If you provide
merge
ormergeFields
, the provided data can be merged into an existing document.Parameter documentRef
A reference to the document to be set.
Parameter data
An object of the fields and values for the document.
Parameter options
An object to configure the set behavior.
Returns
This
Transaction
instance. Used for chaining method calls.Throws
Error - If the provided input is not a valid Firestore document.
method update
update: { <AppModelType, DbModelType extends DocumentData>( documentRef: DocumentReference<AppModelType, DbModelType>, data: UpdateData<DbModelType> ): this; <AppModelType, DbModelType extends DocumentData>( documentRef: DocumentReference<AppModelType, DbModelType>, field: string | FieldPath, value: unknown, ...moreFieldsAndValues: unknown[] ): this;};
Updates fields in the document referred to by the provided DocumentReference. The update will fail if applied to a document that does not exist.
Parameter documentRef
A reference to the document to be updated.
Parameter data
An object containing the fields and values with which to update the document. Fields can contain dots to reference nested fields within the document.
Returns
This
Transaction
instance. Used for chaining method calls.Throws
Error - If the provided input is not valid Firestore data.
Updates fields in the document referred to by the provided DocumentReference. The update will fail if applied to a document that does not exist.
Nested fields can be updated by providing dot-separated field path strings or by providing
FieldPath
objects.Parameter documentRef
A reference to the document to be updated.
Parameter field
The first field to update.
Parameter value
The first value.
Parameter moreFieldsAndValues
Additional key/value pairs.
Returns
This
Transaction
instance. Used for chaining method calls.Throws
Error - If the provided input is not valid Firestore data.
class VectorValue
class VectorValue {}
Represents a vector type in Firestore documents. Create an instance with FieldValue.vector.
VectorValue
class WriteBatch
class WriteBatch {}
A write batch, used to perform multiple writes as a single atomic unit.
A
WriteBatch
object can be acquired by calling writeBatch. It provides methods for adding writes to the write batch. None of the writes will be committed (or visible locally) until WriteBatch.commit is called.
method commit
commit: () => Promise<void>;
Commits all of the writes in this write batch as a single atomic unit.
The result of these writes will only be reflected in document reads that occur after the returned promise resolves. If the client is offline, the write fails. If you would like to see local modifications or buffer writes until the client is online, use the full Firestore SDK.
Returns
A
Promise
resolved once all of the writes in the batch have been successfully written to the backend as an atomic unit (note that it won't resolve while you're offline).
method delete
delete: <AppModelType, DbModelType extends DocumentData>( documentRef: DocumentReference<AppModelType, DbModelType>) => WriteBatch;
Deletes the document referred to by the provided DocumentReference.
Parameter documentRef
A reference to the document to be deleted.
Returns
This
WriteBatch
instance. Used for chaining method calls.
method set
set: { <AppModelType, DbModelType extends DocumentData>( documentRef: DocumentReference<AppModelType, DbModelType>, data: WithFieldValue<AppModelType> ): WriteBatch; <AppModelType, DbModelType extends DocumentData>( documentRef: DocumentReference<AppModelType, DbModelType>, data: PartialWithFieldValue<AppModelType>, options: SetOptions ): WriteBatch;};
Writes to the document referred to by the provided DocumentReference. If the document does not exist yet, it will be created.
Parameter documentRef
A reference to the document to be set.
Parameter data
An object of the fields and values for the document.
Returns
This
WriteBatch
instance. Used for chaining method calls.Writes to the document referred to by the provided DocumentReference. If the document does not exist yet, it will be created. If you provide
merge
ormergeFields
, the provided data can be merged into an existing document.Parameter documentRef
A reference to the document to be set.
Parameter data
An object of the fields and values for the document.
Parameter options
An object to configure the set behavior.
Returns
This
WriteBatch
instance. Used for chaining method calls.Throws
Error - If the provided input is not a valid Firestore document.
method update
update: { <AppModelType, DbModelType extends DocumentData>( documentRef: DocumentReference<AppModelType, DbModelType>, data: UpdateData<DbModelType> ): WriteBatch; <AppModelType, DbModelType extends DocumentData>( documentRef: DocumentReference<AppModelType, DbModelType>, field: string | FieldPath, value: unknown, ...moreFieldsAndValues: unknown[] ): WriteBatch;};
Updates fields in the document referred to by the provided DocumentReference. The update will fail if applied to a document that does not exist.
Parameter documentRef
A reference to the document to be updated.
Parameter data
An object containing the fields and values with which to update the document. Fields can contain dots to reference nested fields within the document.
Returns
This
WriteBatch
instance. Used for chaining method calls.Throws
Error - If the provided input is not valid Firestore data.
Updates fields in the document referred to by this DocumentReference. The update will fail if applied to a document that does not exist.
Nested fields can be update by providing dot-separated field path strings or by providing
FieldPath
objects.Parameter documentRef
A reference to the document to be updated.
Parameter field
The first field to update.
Parameter value
The first value.
Parameter moreFieldsAndValues
Additional key value pairs.
Returns
This
WriteBatch
instance. Used for chaining method calls.Throws
Error - If the provided input is not valid Firestore data.
Interfaces
interface AggregateSpec
interface AggregateSpec {}
Specifies a set of aggregations and their aliases.
index signature
[field: string]: AggregateFieldType;
interface DocumentChange
interface DocumentChange< AppModelType = DocumentData, DbModelType extends DocumentData = DocumentData> {}
A
DocumentChange
represents a change to the documents matching a query. It contains the document affected and the type of change that occurred.
property doc
readonly doc: QueryDocumentSnapshot<AppModelType, DbModelType>;
The document affected by this change.
property newIndex
readonly newIndex: number;
The index of the changed document in the result set immediately after this
DocumentChange
(i.e. supposing that all priorDocumentChange
objects and the currentDocumentChange
object have been applied). Is -1 for 'removed' events.
property oldIndex
readonly oldIndex: number;
The index of the changed document in the result set immediately prior to this
DocumentChange
(i.e. supposing that all priorDocumentChange
objects have been applied). Is-1
for 'added' events.
property type
readonly type: DocumentChangeType;
The type of change ('added', 'modified', or 'removed').
interface DocumentData
interface DocumentData {}
Document data (for use with @firebase/firestore#setDoc) consists of fields mapped to values.
index signature
[field: string]: any;
A mapping between a field and its value.
interface ExperimentalLongPollingOptions
interface ExperimentalLongPollingOptions {}
Options that configure the SDK’s underlying network transport (WebChannel) when long-polling is used.
Note: This interface is "experimental" and is subject to change.
See
FirestoreSettings.experimentalAutoDetectLongPolling
,FirestoreSettings.experimentalForceLongPolling
, andFirestoreSettings.experimentalLongPollingOptions
.
property timeoutSeconds
timeoutSeconds?: number;
The desired maximum timeout interval, in seconds, to complete a long-polling GET response. Valid values are between 5 and 30, inclusive. Floating point values are allowed and will be rounded to the nearest millisecond.
By default, when long-polling is used the "hanging GET" request sent by the client times out after 30 seconds. To request a different timeout from the server, set this setting with the desired timeout.
Changing the default timeout may be useful, for example, if the buffering proxy that necessitated enabling long-polling in the first place has a shorter timeout for hanging GET requests, in which case setting the long-polling timeout to a shorter value, such as 25 seconds, may fix prematurely-closed hanging GET requests. For example, see https://github.com/firebase/firebase-js-sdk/issues/6987.
interface FirestoreDataConverter
interface FirestoreDataConverter< AppModelType, DbModelType extends DocumentData = DocumentData> {}
Converter used by
withConverter()
to transform user objects of typeAppModelType
into Firestore data of typeDbModelType
.Using the converter allows you to specify generic type arguments when storing and retrieving objects from Firestore.
In this context, an "AppModel" is a class that is used in an application to package together related information and functionality. Such a class could, for example, have properties with complex, nested data types, properties used for memoization, properties of types not supported by Firestore (such as
symbol
andbigint
), and helper functions that perform compound operations. Such classes are not suitable and/or possible to store into a Firestore database. Instead, instances of such classes need to be converted to "plain old JavaScript objects" (POJOs) with exclusively primitive properties, potentially nested inside other POJOs or arrays of POJOs. In this context, this type is referred to as the "DbModel" and would be an object suitable for persisting into Firestore. For convenience, applications can implementFirestoreDataConverter
and register the converter with Firestore objects, such asDocumentReference
orQuery
, to automatically convertAppModel
toDbModel
when storing into Firestore, and convertDbModel
toAppModel
when retrieving from Firestore.Example 1
Simple Example
const numberConverter = {toFirestore(value: WithFieldValue<number>) {return { value };},fromFirestore(snapshot: QueryDocumentSnapshot, options: SnapshotOptions) {return snapshot.data(options).value as number;}};async function simpleDemo(db: Firestore): Promise<void> {const documentRef = doc(db, 'values/value123').withConverter(numberConverter);// converters are used with `setDoc`, `addDoc`, and `getDoc`await setDoc(documentRef, 42);const snapshot1 = await getDoc(documentRef);assertEqual(snapshot1.data(), 42);// converters are not used when writing data with `updateDoc`await updateDoc(documentRef, { value: 999 });const snapshot2 = await getDoc(documentRef);assertEqual(snapshot2.data(), 999);}Advanced Example
// The Post class is a model that is used by our application.// This class may have properties and methods that are specific// to our application execution, which do not need to be persisted// to Firestore.class Post {constructor(readonly title: string,readonly author: string,readonly lastUpdatedMillis: number) {}toString(): string {return `${this.title} by ${this.author}`;}}// The PostDbModel represents how we want our posts to be stored// in Firestore. This DbModel has different properties (`ttl`,// `aut`, and `lut`) from the Post class we use in our application.interface PostDbModel {ttl: string;aut: { firstName: string; lastName: string };lut: Timestamp;}// The `PostConverter` implements `FirestoreDataConverter` and specifies// how the Firestore SDK can convert `Post` objects to `PostDbModel`// objects and vice versa.class PostConverter implements FirestoreDataConverter<Post, PostDbModel> {toFirestore(post: WithFieldValue<Post>): WithFieldValue<PostDbModel> {return {ttl: post.title,aut: this._autFromAuthor(post.author),lut: this._lutFromLastUpdatedMillis(post.lastUpdatedMillis)};}fromFirestore(snapshot: QueryDocumentSnapshot, options: SnapshotOptions): Post {const data = snapshot.data(options) as PostDbModel;const author = `${data.aut.firstName} ${data.aut.lastName}`;return new Post(data.ttl, author, data.lut.toMillis());}_autFromAuthor(author: string | FieldValue): { firstName: string; lastName: string } | FieldValue {if (typeof author !== 'string') {// `author` is a FieldValue, so just return it.return author;}const [firstName, lastName] = author.split(' ');return {firstName, lastName};}_lutFromLastUpdatedMillis(lastUpdatedMillis: number | FieldValue): Timestamp | FieldValue {if (typeof lastUpdatedMillis !== 'number') {// `lastUpdatedMillis` must be a FieldValue, so just return it.return lastUpdatedMillis;}return Timestamp.fromMillis(lastUpdatedMillis);}}async function advancedDemo(db: Firestore): Promise<void> {// Create a `DocumentReference` with a `FirestoreDataConverter`.const documentRef = doc(db, 'posts/post123').withConverter(new PostConverter());// The `data` argument specified to `setDoc()` is type checked by the// TypeScript compiler to be compatible with `Post`. Since the `data`// argument is typed as `WithFieldValue<Post>` rather than just `Post`,// this allows properties of the `data` argument to also be special// Firestore values that perform server-side mutations, such as// `arrayRemove()`, `deleteField()`, and `serverTimestamp()`.await setDoc(documentRef, {title: 'My Life',author: 'Foo Bar',lastUpdatedMillis: serverTimestamp()});// The TypeScript compiler will fail to compile if the `data` argument to// `setDoc()` is _not_ compatible with `WithFieldValue<Post>`. This// type checking prevents the caller from specifying objects with incorrect// properties or property values.// @ts-expect-error "Argument of type { ttl: string; } is not assignable// to parameter of type WithFieldValue<Post>"await setDoc(documentRef, { ttl: 'The Title' });// When retrieving a document with `getDoc()` the `DocumentSnapshot`// object's `data()` method returns a `Post`, rather than a generic object,// which would have been returned if the `DocumentReference` did _not_ have a// `FirestoreDataConverter` attached to it.const snapshot1: DocumentSnapshot<Post> = await getDoc(documentRef);const post1: Post = snapshot1.data()!;if (post1) {assertEqual(post1.title, 'My Life');assertEqual(post1.author, 'Foo Bar');}// The `data` argument specified to `updateDoc()` is type checked by the// TypeScript compiler to be compatible with `PostDbModel`. Note that// unlike `setDoc()`, whose `data` argument must be compatible with `Post`,// the `data` argument to `updateDoc()` must be compatible with// `PostDbModel`. Similar to `setDoc()`, since the `data` argument is typed// as `WithFieldValue<PostDbModel>` rather than just `PostDbModel`, this// allows properties of the `data` argument to also be those special// Firestore values, like `arrayRemove()`, `deleteField()`, and// `serverTimestamp()`.await updateDoc(documentRef, {'aut.firstName': 'NewFirstName',lut: serverTimestamp()});// The TypeScript compiler will fail to compile if the `data` argument to// `updateDoc()` is _not_ compatible with `WithFieldValue<PostDbModel>`.// This type checking prevents the caller from specifying objects with// incorrect properties or property values.// @ts-expect-error "Argument of type { title: string; } is not assignable// to parameter of type WithFieldValue<PostDbModel>"await updateDoc(documentRef, { title: 'New Title' });const snapshot2: DocumentSnapshot<Post> = await getDoc(documentRef);const post2: Post = snapshot2.data()!;if (post2) {assertEqual(post2.title, 'My Life');assertEqual(post2.author, 'NewFirstName Bar');}}
method fromFirestore
fromFirestore: ( snapshot: QueryDocumentSnapshot<DocumentData, DocumentData>, options?: SnapshotOptions) => AppModelType;
Called by the Firestore SDK to convert Firestore data into an object of type
AppModelType
. You can access your data by calling:snapshot.data(options)
.Generally, the data returned from
snapshot.data()
can be cast toDbModelType
; however, this is not guaranteed because Firestore does not enforce a schema on the database. For example, writes from a previous version of the application or writes from another client that did not use a type converter could have written data with different properties and/or property types. The implementation will need to choose whether to gracefully recover from non-conforming data or throw an error.To override this method, see .
Parameter snapshot
A
QueryDocumentSnapshot
containing your data and metadata.Parameter options
The
SnapshotOptions
from the initial call todata()
.
method toFirestore
toFirestore: { (modelObject: WithFieldValue<AppModelType>): WithFieldValue<DbModelType>; ( modelObject: PartialWithFieldValue<AppModelType>, options: SetOptions ): PartialWithFieldValue<DbModelType>;};
Called by the Firestore SDK to convert a custom model object of type
AppModelType
into a plain JavaScript object (suitable for writing directly to the Firestore database) of typeDbModelType
. To useset()
withmerge
andmergeFields
,toFirestore()
must be defined withPartialWithFieldValue<AppModelType>
.The
WithFieldValue<T>
type extendsT
to also allow FieldValues such as deleteField to be used as property values.Called by the Firestore SDK to convert a custom model object of type
AppModelType
into a plain JavaScript object (suitable for writing directly to the Firestore database) of typeDbModelType
. Used with setDoc, and withmerge:true
ormergeFields
.The
PartialWithFieldValue<T>
type extendsPartial<T>
to allow FieldValues such as arrayUnion to be used as property values. It also supports nestedPartial
by allowing nested fields to be omitted.
interface FirestoreSettings
interface FirestoreSettings {}
Specifies custom configurations for your Cloud Firestore instance. You must set these before invoking any other methods.
property cacheSizeBytes
cacheSizeBytes?: number;
NOTE: This field will be deprecated in a future major release. Use
cache
field instead to specify cache size, and other cache configurations.An approximate cache size threshold for the on-disk data. If the cache grows beyond this size, Firestore will start removing data that hasn't been recently used. The size is not a guarantee that the cache will stay below that size, only that if the cache exceeds the given size, cleanup will be attempted.
The default value is 40 MB. The threshold must be set to at least 1 MB, and can be set to
CACHE_SIZE_UNLIMITED
to disable garbage collection.
property experimentalAutoDetectLongPolling
experimentalAutoDetectLongPolling?: boolean;
Configures the SDK's underlying transport (WebChannel) to automatically detect if long-polling should be used. This is very similar to
experimentalForceLongPolling
, but only uses long-polling if required.After having had a default value of
false
since its inception in 2019, the default value of this setting was changed in May 2023 totrue
in v9.22.0 of the Firebase JavaScript SDK. That is, auto-detection of long polling is now enabled by default. To disable it, set this setting tofalse
, and please open a GitHub issue to share the problems that motivated you disabling long-polling auto-detection.This setting cannot be used in a Node.js environment.
property experimentalForceLongPolling
experimentalForceLongPolling?: boolean;
Forces the SDK’s underlying network transport (WebChannel) to use long-polling. Each response from the backend will be closed immediately after the backend sends data (by default responses are kept open in case the backend has more data to send). This avoids incompatibility issues with certain proxies, antivirus software, etc. that incorrectly buffer traffic indefinitely. Use of this option will cause some performance degradation though.
This setting cannot be used with
experimentalAutoDetectLongPolling
and may be removed in a future release. If you find yourself using it to work around a specific network reliability issue, please tell us about it in https://github.com/firebase/firebase-js-sdk/issues/1674.This setting cannot be used in a Node.js environment.
property experimentalLongPollingOptions
experimentalLongPollingOptions?: ExperimentalLongPollingOptions;
Options that configure the SDK’s underlying network transport (WebChannel) when long-polling is used.
These options are only used if
experimentalForceLongPolling
is true or ifexperimentalAutoDetectLongPolling
is true and the auto-detection determined that long-polling was needed. Otherwise, these options have no effect.
property host
host?: string;
The hostname to connect to.
property ignoreUndefinedProperties
ignoreUndefinedProperties?: boolean;
Whether to skip nested properties that are set to
undefined
during object serialization. If set totrue
, these properties are skipped and not written to Firestore. If set tofalse
or omitted, the SDK throws an exception when it encounters properties of typeundefined
.
property localCache
localCache?: FirestoreLocalCache;
Specifies the cache used by the SDK. Available options are
MemoryLocalCache
andPersistentLocalCache
, each with different configuration options.When unspecified,
MemoryLocalCache
will be used by default.NOTE: setting this field and
cacheSizeBytes
at the same time will throw exception during SDK initialization. Instead, using the configuration in theFirestoreLocalCache
object to specify the cache size.
property ssl
ssl?: boolean;
Whether to use SSL when connecting.
interface Index
interface Index {}
The SDK definition of a Firestore index.
Modifiers
@beta
Deprecated
Instead of creating cache indexes manually, consider using
enablePersistentCacheIndexAutoCreation()
to let the SDK decide whether to create cache indexes for queries running locally.
property collectionGroup
readonly collectionGroup: string;
The ID of the collection to index.
property fields
readonly fields?: IndexField[];
A list of fields to index.
index signature
[key: string]: unknown;
interface IndexConfiguration
interface IndexConfiguration {}
A list of Firestore indexes to speed up local query execution.
See JSON Format for a description of the format of the index definition.
Modifiers
@beta
Deprecated
Instead of creating cache indexes manually, consider using
enablePersistentCacheIndexAutoCreation()
to let the SDK decide whether to create cache indexes for queries running locally.
property indexes
readonly indexes?: Index[];
A list of all Firestore indexes.
index signature
[key: string]: unknown;
interface IndexField
interface IndexField {}
A single field element in an index configuration.
Modifiers
@beta
Deprecated
Instead of creating cache indexes manually, consider using
enablePersistentCacheIndexAutoCreation()
to let the SDK decide whether to create cache indexes for queries running locally.
property arrayConfig
readonly arrayConfig?: 'CONTAINS';
What type of array index to create. Set to
CONTAINS
forarray-contains
andarray-contains-any
indexes.Only one of
arrayConfig
ororder
should be set;
property fieldPath
readonly fieldPath: string;
The field path to index.
property order
readonly order?: 'ASCENDING' | 'DESCENDING';
What type of array index to create. Set to
ASCENDING
or 'DESCENDING` for==
,!=
,<=
,<=
,in
andnot-in
filters.Only one of
arrayConfig
ororder
should be set.
index signature
[key: string]: unknown;
interface LoadBundleTaskProgress
interface LoadBundleTaskProgress {}
Represents a progress update or a final state from loading bundles.
property bytesLoaded
bytesLoaded: number;
How many bytes have been loaded.
property documentsLoaded
documentsLoaded: number;
How many documents have been loaded.
property taskState
taskState: TaskState;
Current task state.
property totalBytes
totalBytes: number;
How many bytes are in the bundle being loaded.
property totalDocuments
totalDocuments: number;
How many documents are in the bundle being loaded.
interface MemoryCacheSettings
interface MemoryCacheSettings {}
An settings object to configure an
MemoryLocalCache
instance.
property garbageCollector
garbageCollector?: MemoryGarbageCollector;
The garbage collector to use, for the memory cache layer. A
MemoryEagerGarbageCollector
is used when this is undefined.
interface MemoryEagerGarbageCollector
interface MemoryEagerGarbageCollector {}
A garbage collector deletes documents whenever they are not part of any active queries, and have no local mutations attached to them.
This collector tries to ensure lowest memory footprints from the SDK, at the risk of documents not being cached for offline queries or for direct queries to the cache.
Use factory function to create an instance of this collector.
property kind
kind: 'memoryEager';
interface MemoryLocalCache
interface MemoryLocalCache {}
Provides an in-memory cache to the SDK. This is the default cache unless explicitly configured otherwise.
To use, create an instance using the factory function , then set the instance to
FirestoreSettings.cache
and callinitializeFirestore
using the settings object.
property kind
kind: 'memory';
interface MemoryLruGarbageCollector
interface MemoryLruGarbageCollector {}
A garbage collector deletes Least-Recently-Used documents in multiple batches.
This collector is configured with a target size, and will only perform collection when the cached documents exceed the target size. It avoids querying backend repeated for the same query or document, at the risk of having a larger memory footprint.
Use factory function to create a instance of this collector.
property kind
kind: 'memoryLru';
interface PersistenceSettings
interface PersistenceSettings {}
Settings that can be passed to
enableIndexedDbPersistence()
to configure Firestore persistence.Persistence cannot be used in a Node.js environment.
property forceOwnership
forceOwnership?: boolean;
Whether to force enable persistence for the client. This cannot be used with multi-tab synchronization and is primarily intended for use with Web Workers. Setting this to
true
will enable persistence, but cause other tabs using persistence to fail.
interface PersistentCacheSettings
interface PersistentCacheSettings {}
An settings object to configure an
PersistentLocalCache
instance.Persistent cache cannot be used in a Node.js environment.
property cacheSizeBytes
cacheSizeBytes?: number;
An approximate cache size threshold for the on-disk data. If the cache grows beyond this size, Firestore will start removing data that hasn't been recently used. The SDK does not guarantee that the cache will stay below that size, only that if the cache exceeds the given size, cleanup will be attempted.
The default value is 40 MB. The threshold must be set to at least 1 MB, and can be set to
CACHE_SIZE_UNLIMITED
to disable garbage collection.
property tabManager
tabManager?: PersistentTabManager;
Specifies how multiple tabs/windows will be managed by the SDK.
interface PersistentLocalCache
interface PersistentLocalCache {}
Provides a persistent cache backed by IndexedDb to the SDK.
To use, create an instance using the factory function , then set the instance to
FirestoreSettings.cache
and callinitializeFirestore
using the settings object.
property kind
kind: 'persistent';
interface PersistentMultipleTabManager
interface PersistentMultipleTabManager {}
A tab manager supporting multiple tabs. SDK will synchronize queries and mutations done across all tabs using the SDK.
property kind
kind: 'PersistentMultipleTab';
interface PersistentSingleTabManager
interface PersistentSingleTabManager {}
A tab manager supporting only one tab, no synchronization will be performed across tabs.
property kind
kind: 'persistentSingleTab';
interface PersistentSingleTabManagerSettings
interface PersistentSingleTabManagerSettings {}
Type to configure an
PersistentSingleTabManager
instance.
property forceOwnership
forceOwnership?: boolean;
Whether to force-enable persistent (IndexedDB) cache for the client. This cannot be used with multi-tab synchronization and is primarily intended for use with Web Workers. Setting this to
true
will enable IndexedDB, but cause other tabs using IndexedDB cache to fail.
interface SnapshotListenOptions
interface SnapshotListenOptions {}
An options object that can be passed to onSnapshot and QuerySnapshot.docChanges to control which types of changes to include in the result set.
property includeMetadataChanges
readonly includeMetadataChanges?: boolean;
Include a change even if only the metadata of the query or of a document changed. Default is false.
property source
readonly source?: ListenSource;
Set the source the query listens to. Default to "default", which listens to both cache and server.
interface SnapshotOptions
interface SnapshotOptions {}
Options that configure how data is retrieved from a
DocumentSnapshot
(for example the desired behavior for server timestamps that have not yet been set to their final value).
property serverTimestamps
readonly serverTimestamps?: 'estimate' | 'previous' | 'none';
If set, controls the return value for server timestamps that have not yet been set to their final value.
By specifying 'estimate', pending server timestamps return an estimate based on the local clock. This estimate will differ from the final value and cause these values to change once the server result becomes available.
By specifying 'previous', pending timestamps will be ignored and return their previous value instead.
If omitted or set to 'none',
null
will be returned by default until the server value becomes available.
interface TransactionOptions
interface TransactionOptions {}
Options to customize transaction behavior.
property maxAttempts
readonly maxAttempts?: number;
Maximum number of attempts to commit, after which transaction fails. Default is 5.
interface Unsubscribe
interface Unsubscribe {}
A function returned by
onSnapshot()
that removes the listener when invoked.
call signature
(): void;
Removes the listener when invoked.
Type Aliases
type AddPrefixToKeys
type AddPrefixToKeys<Prefix extends string, T extends Record<string, unknown>> = { [K in keyof T & string as `${Prefix}.${K}`]+?: string extends K ? any : T[K];};
Returns a new map where every key is prefixed with the outer key appended to a dot.
type AggregateFieldType
type AggregateFieldType = | ReturnType<typeof sum> | ReturnType<typeof average> | ReturnType<typeof count>;
The union of all
AggregateField
types that are supported by Firestore.
type AggregateSpecData
type AggregateSpecData<T extends AggregateSpec> = { [P in keyof T]: T[P] extends AggregateField<infer U> ? U : never;};
A type whose keys are taken from an
AggregateSpec
, and whose values are the result of the aggregation performed by the correspondingAggregateField
from the inputAggregateSpec
.
type AggregateType
type AggregateType = 'count' | 'avg' | 'sum';
Union type representing the aggregate type to be performed.
type ChildUpdateFields
type ChildUpdateFields<K extends string, V> = V extends Record<string, unknown> ? AddPrefixToKeys<K, UpdateData<V>> : never;
Helper for calculating the nested fields for a given type T1. This is needed to distribute union types such as
undefined | {...}
(happens for optional props) or{a: A} | {b: B}
.In this use case,
V
is used to distribute the union types ofT[K]
onRecord
, sinceT[K]
is evaluated as an expression and not distributed.See https://www.typescriptlang.org/docs/handbook/advanced-types.html#distributive-conditional-types
type DocumentChangeType
type DocumentChangeType = 'added' | 'removed' | 'modified';
The type of a
DocumentChange
may be 'added', 'removed', or 'modified'.
type FirestoreErrorCode
type FirestoreErrorCode = | 'cancelled' | 'unknown' | 'invalid-argument' | 'deadline-exceeded' | 'not-found' | 'already-exists' | 'permission-denied' | 'resource-exhausted' | 'failed-precondition' | 'aborted' | 'out-of-range' | 'unimplemented' | 'internal' | 'unavailable' | 'data-loss' | 'unauthenticated';
The set of Firestore status codes. The codes are the same at the ones exposed by gRPC here: https://github.com/grpc/grpc/blob/master/doc/statuscodes.md
Possible values: - 'cancelled': The operation was cancelled (typically by the caller). - 'unknown': Unknown error or an error from a different error domain. - 'invalid-argument': Client specified an invalid argument. Note that this differs from 'failed-precondition'. 'invalid-argument' indicates arguments that are problematic regardless of the state of the system (e.g. an invalid field name). - 'deadline-exceeded': Deadline expired before operation could complete. For operations that change the state of the system, this error may be returned even if the operation has completed successfully. For example, a successful response from a server could have been delayed long enough for the deadline to expire. - 'not-found': Some requested document was not found. - 'already-exists': Some document that we attempted to create already exists. - 'permission-denied': The caller does not have permission to execute the specified operation. - 'resource-exhausted': Some resource has been exhausted, perhaps a per-user quota, or perhaps the entire file system is out of space. - 'failed-precondition': Operation was rejected because the system is not in a state required for the operation's execution. - 'aborted': The operation was aborted, typically due to a concurrency issue like transaction aborts, etc. - 'out-of-range': Operation was attempted past the valid range. - 'unimplemented': Operation is not implemented or not supported/enabled. - 'internal': Internal errors. Means some invariants expected by underlying system has been broken. If you see one of these errors, something is very broken. - 'unavailable': The service is currently unavailable. This is most likely a transient condition and may be corrected by retrying with a backoff. - 'data-loss': Unrecoverable data loss or corruption. - 'unauthenticated': The request does not have valid authentication credentials for the operation.
type FirestoreLocalCache
type FirestoreLocalCache = MemoryLocalCache | PersistentLocalCache;
Union type from all supported SDK cache layer.
type ListenSource
type ListenSource = 'default' | 'cache';
Describe the source a query listens to.
Set to
default
to listen to both cache and server changes. Set tocache
to listen to changes in cache only.
type MemoryGarbageCollector
type MemoryGarbageCollector = | MemoryEagerGarbageCollector | MemoryLruGarbageCollector;
Union type from all support garbage collectors for memory local cache.
type NestedUpdateFields
type NestedUpdateFields<T extends Record<string, unknown>> = UnionToIntersection< { [K in keyof T & string]: ChildUpdateFields<K, T[K]>; }[keyof T & string]>;
For each field (e.g. 'bar'), find all nested keys (e.g. {'bar.baz': T1, 'bar.qux': T2}). Intersect them together to make a single map containing all possible keys that are all marked as optional
type OrderByDirection
type OrderByDirection = 'desc' | 'asc';
The direction of a orderBy clause is specified as 'desc' or 'asc' (descending or ascending).
type PartialWithFieldValue
type PartialWithFieldValue<T> = | Partial<T> | (T extends Primitive ? T : T extends {} ? { [K in keyof T]?: PartialWithFieldValue<T[K]> | FieldValue; } : never);
Similar to TypeScript's
Partial<T>
, but allows nested fields to be omitted and FieldValues to be passed in as property values.
type PersistentTabManager
type PersistentTabManager = | PersistentSingleTabManager | PersistentMultipleTabManager;
A union of all available tab managers.
type Primitive
type Primitive = string | number | boolean | undefined | null;
Primitive types.
type QueryConstraintType
type QueryConstraintType = | 'where' | 'orderBy' | 'limit' | 'limitToLast' | 'startAt' | 'startAfter' | 'endAt' | 'endBefore';
Describes the different query constraints available in this SDK.
type QueryFilterConstraint
type QueryFilterConstraint = | QueryFieldFilterConstraint | QueryCompositeFilterConstraint;
QueryFilterConstraint
is a helper union type that represents QueryFieldFilterConstraint and QueryCompositeFilterConstraint.
type QueryNonFilterConstraint
type QueryNonFilterConstraint = | QueryOrderByConstraint | QueryLimitConstraint | QueryStartAtConstraint | QueryEndAtConstraint;
QueryNonFilterConstraint
is a helper union type that represents QueryConstraints which are used to narrow or order the set of documents, but that do not explicitly filter on a document field.QueryNonFilterConstraint
s are created by invoking orderBy, startAt, startAfter, endBefore, endAt, limit or limitToLast and can then be passed to query to create a new query instance that also contains theQueryConstraint
.
type SetOptions
type SetOptions = | { readonly merge?: boolean; } | { readonly mergeFields?: Array<string | FieldPath>; };
An options object that configures the behavior of @firebase/firestore#setDoc, and calls. These calls can be configured to perform granular merges instead of overwriting the target documents in their entirety by providing a
SetOptions
withmerge: true
.Parameter merge
Changes the behavior of a
setDoc()
call to only replace the values specified in its data argument. Fields omitted from thesetDoc()
call remain untouched. If your input sets any field to an empty map, all nested fields are overwritten.Parameter mergeFields
Changes the behavior of
setDoc()
calls to only replace the specified field paths. Any field path that is not specified is ignored and remains untouched. If your input sets any field to an empty map, all nested fields are overwritten.
type TaskState
type TaskState = 'Error' | 'Running' | 'Success';
Represents the state of bundle loading tasks.
Both 'Error' and 'Success' are sinking state: task will abort or complete and there will be no more updates after they are reported.
type UnionToIntersection
type UnionToIntersection<U> = (U extends unknown ? (k: U) => void : never) extends ( k: infer I) => void ? I : never;
Given a union type
U = T1 | T2 | ...
, returns an intersected type(T1 & T2 & ...)
.Uses distributive conditional types and inference from conditional types. This works because multiple candidates for the same type variable in contra-variant positions causes an intersection type to be inferred. https://www.typescriptlang.org/docs/handbook/advanced-types.html#type-inference-in-conditional-types https://stackoverflow.com/questions/50374908/transform-union-type-to-intersection-type
type UpdateData
type UpdateData<T> = T extends Primitive ? T : T extends {} ? { [K in keyof T]?: UpdateData<T[K]> | FieldValue; } & NestedUpdateFields<T> : Partial<T>;
Update data (for use with updateDoc) that consists of field paths (e.g. 'foo' or 'foo.baz') mapped to values. Fields that contain dots reference nested fields within the document. FieldValues can be passed in as property values.
type WhereFilterOp
type WhereFilterOp = | '<' | '<=' | '==' | '!=' | '>=' | '>' | 'array-contains' | 'in' | 'array-contains-any' | 'not-in';
Filter conditions in a where clause are specified using the strings '<', '<=', '==', '!=', '>=', '>', 'array-contains', 'in', 'array-contains-any', and 'not-in'.
type WithFieldValue
type WithFieldValue<T> = | T | (T extends Primitive ? T : T extends {} ? { [K in keyof T]: WithFieldValue<T[K]> | FieldValue; } : never);
Allows FieldValues to be passed in as a property value while maintaining type safety.
Package Files (1)
Dependencies (7)
Dev Dependencies (20)
- @firebase/app
- @firebase/app-compat
- @firebase/auth
- @rollup/plugin-alias
- @rollup/plugin-json
- @types/eslint
- @types/json-stable-stringify
- chai-exclude
- json-stable-stringify
- protobufjs
- rollup
- rollup-plugin-copy
- rollup-plugin-copy-assets
- rollup-plugin-dts
- rollup-plugin-replace
- rollup-plugin-sourcemaps
- rollup-plugin-terser
- rollup-plugin-typescript2
- ts-node
- typescript
Peer Dependencies (1)
Badge
To add a badge like this oneto your package's README, use the codes available below.
You may also use Shields.io to create a custom badge linking to https://www.jsdocs.io/package/@firebase/firestore
.
- Markdown[![jsDocs.io](https://img.shields.io/badge/jsDocs.io-reference-blue)](https://www.jsdocs.io/package/@firebase/firestore)
- HTML<a href="https://www.jsdocs.io/package/@firebase/firestore"><img src="https://img.shields.io/badge/jsDocs.io-reference-blue" alt="jsDocs.io"></a>
- Updated .
Package analyzed in 15017 ms. - Missing or incorrect documentation? Open an issue for this package.