@firebase/firestore

Funciones

Función Descripción
función (aplicación...)
getFirestore (aplicación) Devuelve la instancia predeterminada existente de Firestore que está asociada con la FirebaseApp proporcionada. . Si no existe ninguna instancia, inicializa una nueva instancia con la configuración predeterminada.
getFirestore(aplicación, ID de base de datos) (BETA) Devuelve la instancia de Firestore con nombre existente que está asociada con la FirebaseApp proporcionada . Si no existe ninguna instancia, inicializa una nueva instancia con la configuración predeterminada.
inicializarFirestore(aplicación, configuración, ID de base de datos) Inicializa una nueva instancia de Firestore con la configuración proporcionada. Solo se puede llamar antes que cualquier otra función, incluida getFirestore() . Si la configuración personalizada está vacía, esta función equivale a llamar a getFirestore() .
función (almacén de fuego...)
clearIndexedDbPersistence(firestore) Borra el almacenamiento persistente. Esto incluye escrituras pendientes y documentos almacenados en caché. Se debe llamar mientras la instancia de Firestore no está iniciada (después de finalizar la aplicación o cuando la aplicación se inicializa por primera vez). Al inicio, esta función debe llamarse antes que otras funciones (que no sean initializeFirestore() o getFirestore() )). Si la instancia de Firestore aún se está ejecutando, la promesa se rechazará con el código de error de failed-precondition . Nota: clearIndexedDbPersistence() está destinado principalmente a ayudar a escribir pruebas confiables que utilicen Cloud Firestore. Utiliza un mecanismo eficiente para descartar datos existentes, pero no intenta sobrescribirlos de forma segura ni hacer que los datos almacenados en caché sean irrecuperables. Para las aplicaciones que son sensibles a la divulgación de datos almacenados en caché entre sesiones de usuario, recomendamos encarecidamente no habilitar la persistencia en absoluto.
colección (firestore, ruta, segmentos de ruta) Obtiene una instancia CollectionReference que hace referencia a la colección en la ruta absoluta especificada.
grupo de colección (firestore, ID de colección) Crea y devuelve una nueva instancia Query que incluye todos los documentos de la base de datos contenidos en una colección o subcolección con el collectionId dado.
connectFirestoreEmulator(firestore, host, puerto, opciones) Modifique esta instancia para comunicarse con el emulador de Cloud Firestore. Nota: Esto debe llamarse antes de que esta instancia se haya utilizado para realizar cualquier operación.
desactivarRed(firestore) Deshabilita el uso de la red para esta instancia. Se puede volver a habilitar a través de enableNetwork() . Mientras la red esté deshabilitada, cualquier escucha de instantáneas, llamadas getDoc() o getDocs() devolverán resultados del caché y cualquier operación de escritura se pondrá en cola hasta que se restaure la red.
doc(firestore, ruta, segmentos de ruta) Obtiene una instancia DocumentReference que hace referencia al documento en la ruta absoluta especificada.
enableIndexedDbPersistence(firestore, persistenceSettings) Intenta habilitar el almacenamiento persistente, si es posible. Debe llamarse antes que cualquier otra función (que no sea inicializeFirestore() , getFirestore() o clearIndexedDbPersistence() . Si esto falla, enableIndexedDbPersistence() rechazará la promesa que devuelve. Tenga en cuenta que incluso después de este error, la instancia de Firestore seguirá siendo utilizable; sin embargo, la persistencia sin conexión estará deshabilitada. Hay varias razones por las que esto puede fallar, que pueden identificarse mediante el code del error. * condición previa fallida: la aplicación ya está abierta en otra pestaña del navegador. * no implementado: el navegador es incompatible con la implementación de persistencia fuera de línea. La persistencia no se puede utilizar en un entorno Node.js.
enableMultiTabIndexedDbPersistence (firestore) Intenta habilitar el almacenamiento persistente de varias pestañas, si es posible. Si se habilita en todas las pestañas, todas las operaciones comparten el acceso a la persistencia local, incluida la ejecución compartida de consultas y actualizaciones de documentos locales con latencia compensada en todas las instancias conectadas. Si esto falla, enableMultiTabIndexedDbPersistence() rechazará la promesa que devuelve. Tenga en cuenta que incluso después de este error, la instancia de Firestore seguirá siendo utilizable; sin embargo, la persistencia sin conexión estará deshabilitada. Hay varias razones por las que esto puede fallar, que pueden identificarse mediante el code del error. * condición previa fallida: la aplicación ya está abierta en otra pestaña del navegador y la función de pestañas múltiples no está habilitada. * no implementado: el navegador es incompatible con la implementación de persistencia fuera de línea.
habilitarNetwork(firestore) Vuelve a habilitar el uso de la red para esta instancia de Firestore después de una llamada previa a enableNetwork() .
getPersistentCacheIndexManager(firestore) Devuelve el administrador de índices PersistentCache utilizado por el objeto Firestore determinado. La instancia PersistentCacheIndexManager , o null si el almacenamiento persistente local no está en uso.
loadBundle(firestore, datos del paquete) Carga un paquete de Firestore en la caché local.
consulta nombrada (firestore, nombre) Lee una consulta de Firestore desde la caché local, identificada por el nombre de pila. Las consultas nombradas se empaquetan en paquetes en el lado del servidor (junto con los documentos resultantes) y se cargan en la caché local mediante loadBundle . Una vez en la caché local, utilice este método para extraer una consulta por nombre.
onSnapshotsInSync (firestore, observador) Adjunta un oyente para un evento de instantáneas sincronizadas. El evento de instantáneas sincronizadas indica que todos los oyentes afectados por un cambio determinado se han activado, incluso si un único cambio generado por el servidor afecta a varios oyentes. NOTA: El evento de instantáneas sincronizadas solo indica que los oyentes están sincronizados entre sí, pero no se relaciona con si esas instantáneas están sincronizadas con el servidor. Utilice SnapshotMetadata en los oyentes individuales para determinar si una instantánea proviene de la memoria caché o del servidor.
onSnapshotsInSync (firestore, onSync) Adjunta un oyente para un evento de instantáneas sincronizadas. El evento de instantáneas sincronizadas indica que todos los oyentes afectados por un cambio determinado se han activado, incluso si un único cambio generado por el servidor afecta a varios oyentes. NOTA: El evento de instantáneas sincronizadas solo indica que los oyentes están sincronizados entre sí, pero no se relaciona con si esas instantáneas están sincronizadas con el servidor. Utilice SnapshotMetadata en los oyentes individuales para determinar si una instantánea proviene de la memoria caché o del servidor.
runTransaction(firestore, updateFunction, opciones) Ejecuta la updateFunction dada y luego intenta confirmar los cambios aplicados dentro de la transacción. Si algún documento leído dentro de la transacción ha cambiado, Cloud Firestore vuelve a intentar la updateFunction . Si no se confirma después de 5 intentos, la transacción falla. El número máximo de escrituras permitidas en una sola transacción es 500.
setIndexConfiguration (firestore, configuración) (BETA) Configura la indexación para la ejecución de consultas locales. Se anula cualquier configuración de índice anterior. La Promise se resuelve una vez que se ha persistido la configuración del índice. Las propias entradas del índice se crean de forma asincrónica. Puede seguir utilizando consultas que requieran indexación incluso si los índices aún no están disponibles. La ejecución de la consulta comenzará automáticamente a utilizar el índice una vez que se hayan escrito las entradas del índice. Los índices solo se admiten con persistencia IndexedDb. Si IndexedDb no está habilitado, se ignora cualquier configuración de índice.
setIndexConfiguration(firestore, json) (BETA) Configura la indexación para la ejecución de consultas locales. Se anula cualquier configuración de índice anterior. La Promise se resuelve una vez que se ha persistido la configuración del índice. Las propias entradas del índice se crean de forma asincrónica. Puede seguir utilizando consultas que requieran indexación incluso si los índices aún no están disponibles. La ejecución de la consulta comenzará automáticamente a utilizar el índice una vez que se hayan escrito las entradas del índice. Los índices solo se admiten con persistencia IndexedDb. Invoque enableIndexedDbPersistence() o enableMultiTabIndexedDbPersistence() antes de establecer una configuración de índice. Si IndexedDb no está habilitado, se ignora cualquier configuración de índice. El método acepta el formato JSON exportado por Firebase CLI ( firebase firestore:indexes ). Si el formato JSON no es válido, este método arroja un error.
terminar (firestore) Termina la instancia de Firestore proporcionada. Después de llamar terminate() solo se puede utilizar la función clearIndexedDbPersistence() . Cualquier otra función arrojará un FirestoreError . Para reiniciar después de la terminación, cree una nueva instancia de FirebaseFirestore con getFirestore() . La terminación no cancela ninguna escritura pendiente y ninguna promesa que esté esperando una respuesta del servidor no se resolverá. Si tiene habilitada la persistencia, la próxima vez que inicie esta instancia, reanudará el envío de estas escrituras al servidor. Nota: En circunstancias normales, no es necesario llamar terminate() . Esta función es útil solo cuando desea forzar que esta instancia libere todos sus recursos o en combinación con clearIndexedDbPersistence() para garantizar que todo el estado local se destruya entre ejecuciones de prueba.
esperar para escrituras pendientes (firestore) Espera hasta que el backend haya reconocido todas las escrituras actualmente pendientes para el usuario activo. La promesa devuelta se resuelve inmediatamente si no hay escrituras pendientes. De lo contrario, la promesa espera todas las escrituras emitidas anteriormente (incluidas las escritas en una sesión de aplicación anterior), pero no espera las escrituras que se agregaron después de llamar a la función. Si desea esperar escrituras adicionales, llame nuevamente waitForPendingWrites() . Cualquier promesa pendiente de waitForPendingWrites() se rechaza durante los cambios de usuario.
escribir lote (firestore) Crea un lote de escritura, utilizado para realizar múltiples escrituras como una única operación atómica. El número máximo de escrituras permitidas en un único WriteBatch es 500. A diferencia de las transacciones, los lotes de escritura persisten fuera de línea y, por lo tanto, son preferibles cuando no necesita condicionar sus escrituras a los datos leídos.
función()
contar() Cree un objeto AggregateField que pueda usarse para calcular el recuento de documentos en el conjunto de resultados de una consulta.
eliminar campo() Devuelve un centinela para usar con updateDoc() o setDoc() con {merge: true} para marcar un campo para su eliminación.
documentoId() Devuelve un FieldPath centinela especial para hacer referencia al ID de un documento. Se puede utilizar en consultas para ordenar o filtrar por ID del documento.
obtenerFirestore() Devuelve la instancia de Firestore predeterminada existente que está asociada con la FirebaseApp predeterminada . Si no existe ninguna instancia, inicializa una nueva instancia con la configuración predeterminada.
memoriaEagerGarbageCollector() Crea una instancia de MemoryEagerGarbageCollector . Este también es el recolector de basura predeterminado a menos que se especifique explícitamente lo contrario.
persistenteMultipleTabManager() Crea una instancia de PersistentMultipleTabManager .
marca de tiempo del servidor() Devuelve un centinela usado con setDoc() o updateDoc() para incluir una marca de tiempo generada por el servidor en los datos escritos.
función (ID de base de datos...)
getFirestore(ID de base de datos) (BETA) Devuelve la instancia de Firestore con nombre existente que está asociada con la FirebaseApp predeterminada . Si no existe ninguna instancia, inicializa una nueva instancia con la configuración predeterminada.
función(elementos...)
matrizEliminar(elementos) Devuelve un valor especial que se puede usar con setDoc() o que le dice al servidor que elimine los elementos dados de cualquier valor de matriz que ya exista en el servidor. Todas las instancias de cada elemento especificado se eliminarán de la matriz. Si el campo que se está modificando aún no es una matriz, se sobrescribirá con una matriz vacía.
matrizUnión(elementos) Devuelve un valor especial que se puede utilizar con setDoc() o updateDoc() que le indica al servidor que una los elementos dados con cualquier valor de matriz que ya exista en el servidor. Cada elemento especificado que aún no exista en la matriz se agregará al final. Si el campo que se está modificando aún no es una matriz, se sobrescribirá con una matriz que contenga exactamente los elementos especificados.
función(campo...)
promedio (campo) Cree un objeto AggregateField que pueda usarse para calcular el promedio de un campo específico en un rango de documentos en el conjunto de resultados de una consulta.
suma (campo) Cree un objeto AggregateField que pueda usarse para calcular la suma de un campo específico en un rango de documentos en el conjunto de resultados de una consulta.
función(rutadelcampo...)
ordenar por (ruta del campo, cadena de dirección) Crea un QueryOrderByConstraint que ordena el resultado de la consulta por el campo especificado, opcionalmente en orden descendente en lugar de ascendente. Nota: Los documentos que no contengan el campo especificado no estarán presentes en el resultado de la consulta.
donde(rutacampo, opStr, valor) Crea un QueryFieldFilterConstraint que exige que los documentos deben contener el campo especificado y que el valor debe satisfacer la restricción de relación proporcionada.
función (valores de campo...)
final en (valores de campo) Crea un QueryEndAtConstraint que modifica el conjunto de resultados para que finalice en los campos proporcionados en relación con el orden de la consulta. El orden de los valores de los campos debe coincidir con el orden de las cláusulas de orden por de la consulta.
finalizar antes (valores de campo) Crea un QueryEndAtConstraint que modifica el conjunto de resultados para que finalice antes de los campos proporcionados en relación con el orden de la consulta. El orden de los valores de los campos debe coincidir con el orden de las cláusulas de orden por de la consulta.
empezar después (valores de campo) Crea un QueryStartAtConstraint que modifica el conjunto de resultados para que comience después de los campos proporcionados en relación con el orden de la consulta. El orden de los valores de los campos debe coincidir con el orden de las cláusulas de orden por de la consulta.
inicio en (valores de campo) Crea un QueryStartAtConstraint que modifica el conjunto de resultados para comenzar en los campos proporcionados en relación con el orden de la consulta. El orden de los valores de los campos debe coincidir con el orden de las cláusulas de orden por de la consulta.
función (administrador de índices...)
eliminarAllPersistentCacheIndexes(indexManager) Elimina todos los índices de caché persistentes. Tenga en cuenta que esta función también eliminará los índices generados por setIndexConfiguration() , que está en desuso.
desactivarPersistentCacheIndexAutoCreation(indexManager) Deja de crear índices de caché persistentes automáticamente para la ejecución de consultas locales. Los índices que se crearon llamando enablePersistentCacheIndexAutoCreation() aún tienen efecto.
enablePersistentCacheIndexAutoCreation(indexManager) Permite que el SDK cree automáticamente índices de caché persistentes para la ejecución de consultas locales cuando el SDK cree que los índices de caché pueden ayudar a mejorar el rendimiento. Esta función esta desactivada por defecto.
función (izquierda...)
agregadoFieldEqual(izquierda, derecha) Compara dos 'AggregateField ` instancias para la igualdad.
agregadoQuerySnapshotEqual(izquierda, derecha) Compara dos instancias AggregateQuerySnapshot para determinar la igualdad. Dos instancias AggregateQuerySnapshot se consideran "iguales" si tienen consultas subyacentes que comparan datos iguales y iguales.
consultaIgual(izquierda, derecha) Devuelve verdadero si las consultas proporcionadas apuntan a la misma colección y aplican las mismas restricciones.
refEqual(izquierda, derecha) Devuelve verdadero si las referencias proporcionadas son iguales.
instantáneaEqual(izquierda, derecha) Devuelve verdadero si las instantáneas proporcionadas son iguales.
función(límite...)
límite(límite) Crea un QueryLimitConstraint que solo devuelve los primeros documentos coincidentes.
límite al último (límite) Crea un QueryLimitConstraint que solo devuelve los últimos documentos coincidentes. Debe especificar al menos una cláusula orderBy para las consultas limitToLast ; de lo contrario, se generará una excepción durante la ejecución.
función(nivel de registro...)
setLogLevel(logLevel) Establece el nivel de detalle de los registros de Cloud Firestore (depuración, error o silencio).
función(n...)
incremento(n) Devuelve un valor especial que se puede utilizar con setDoc() o updateDoc() que le indica al servidor que incremente el valor actual del campo en el valor dado. Si el operando o el valor del campo actual utiliza precisión de punto flotante, toda la aritmética sigue la semántica IEEE 754. Si ambos valores son enteros, los valores fuera del rango de números seguros de JavaScript ( Number.MIN_SAFE_INTEGER a Number.MAX_SAFE_INTEGER ) también están sujetos a pérdida de precisión. Además, una vez procesadas por el backend de Firestore, todas las operaciones con números enteros tienen un límite entre -2^63 y 2^63-1. Si el valor del campo actual no es del tipo number , o si el campo aún no existe, la transformación establece el campo en el valor dado.
función(consulta...)
getAggregateFromServer (consulta, especificación agregada) Calcula las agregaciones especificadas sobre los documentos en el conjunto de resultados de la consulta dada, sin descargar realmente los documentos. Usar esta función para realizar agregaciones es eficiente porque solo se descargan los valores de agregación finales, no los datos de los documentos. Esta función puede incluso realizar agregaciones de documentos si el conjunto de resultados fuera prohibitivamente grande para descargarlo por completo (por ejemplo, miles de documentos). El resultado recibido del servidor se presenta inalterado, sin considerar ningún estado local. Es decir, no se tienen en cuenta los documentos en la caché local ni las modificaciones locales que aún no estén sincronizadas con el servidor. Los resultados descargados previamente, si los hay, no se utilizan: cada solicitud que utiliza esta fuente implica necesariamente un viaje de ida y vuelta al servidor.
getCountFromServer(consulta) Calcula la cantidad de documentos en el conjunto de resultados de la consulta dada, sin descargar los documentos. Usar esta función para contar los documentos es eficiente porque solo se descarga el recuento final, no los datos de los documentos. Esta función puede incluso contar los documentos si el conjunto de resultados fuera prohibitivamente grande para descargarlo por completo (por ejemplo, miles de documentos). El resultado recibido del servidor se presenta inalterado, sin considerar ningún estado local. Es decir, no se tienen en cuenta los documentos en la caché local ni las modificaciones locales que aún no estén sincronizadas con el servidor. Los resultados descargados previamente, si los hay, no se utilizan: cada solicitud que utiliza esta fuente implica necesariamente un viaje de ida y vuelta al servidor.
obtenerDocs(consulta) Ejecuta la consulta y devuelve los resultados como QuerySnapshot . Nota: getDocs() intenta proporcionar datos actualizados cuando es posible esperando datos del servidor, pero puede devolver datos almacenados en caché o fallar si no está conectado y no se puede acceder al servidor. Para especificar este comportamiento, invoque getDocsFromCache() o getDocsFromServer() .
getDocsFromCache(consulta) Ejecuta la consulta y devuelve los resultados como una QuerySnapshot desde la memoria caché. Devuelve un conjunto de resultados vacío si actualmente no hay en caché ningún documento que coincida con la consulta.
getDocsFromServer (consulta) Ejecuta la consulta y devuelve los resultados como una QuerySnapshot del servidor. Devuelve un error si la red no está disponible.
onSnapshot (consulta, observador) Adjunta un detector para eventos QuerySnapshot . Puede pasar devoluciones de llamada onNext y onError individuales o pasar un único objeto observador con devoluciones de llamada next y error . El oyente se puede cancelar llamando a la función que se devuelve cuando se llama a onSnapshot . NOTA: Aunque se puede proporcionar una devolución de llamada onCompletion , nunca se llamará porque la secuencia de instantáneas es interminable.
onSnapshot(consulta, opciones, observador) Adjunta un detector para eventos QuerySnapshot . Puede pasar devoluciones de llamada onNext y onError individuales o pasar un único objeto observador con devoluciones de llamada next y error . El oyente se puede cancelar llamando a la función que se devuelve cuando se llama a onSnapshot . NOTA: Aunque se puede proporcionar una devolución de llamada onCompletion , nunca se llamará porque la secuencia de instantáneas es interminable.
onSnapshot(consulta, onSiguiente, onError, onCompletion) Adjunta un detector para eventos QuerySnapshot . Puede pasar devoluciones de llamada onNext y onError individuales o pasar un único objeto observador con devoluciones de llamada next y error . El oyente se puede cancelar llamando a la función que se devuelve cuando se llama a onSnapshot . NOTA: Aunque se puede proporcionar una devolución de llamada onCompletion , nunca se llamará porque la secuencia de instantáneas es interminable.
onSnapshot(consulta, opciones, onNext, onError, onCompletion) Adjunta un detector para eventos QuerySnapshot . Puede pasar devoluciones de llamada onNext y onError individuales o pasar un único objeto observador con devoluciones de llamada next y error . El oyente se puede cancelar llamando a la función que se devuelve cuando se llama a onSnapshot . NOTA: Aunque se puede proporcionar una devolución de llamada onCompletion , nunca se llamará porque la secuencia de instantáneas es interminable.
consulta (consulta, filtro compuesto, restricciones de consulta) Crea una nueva instancia inmutable de Query que se extiende para incluir también restricciones de consulta adicionales.
consulta (consulta, consultaRestricciones) Crea una nueva instancia inmutable de Query que se extiende para incluir también restricciones de consulta adicionales.
función (consultaRestricciones...)
y (restricciones de consulta) Crea una nueva QueryCompositeFilterConstraint que es una conjunción de las restricciones de filtro dadas. Un filtro de conjunción incluye un documento si satisface todos los filtros dados.
o (consultaRestricciones) Crea una nueva QueryCompositeFilterConstraint que es una disyunción de las restricciones de filtro dadas. Un filtro de disyunción incluye un documento si satisface alguno de los filtros dados.
función(referencia...)
addDoc(referencia, datos) Agregue un nuevo documento a CollectionReference especificada con los datos proporcionados, asignándole un ID de documento automáticamente.
colección (referencia, ruta, segmentos de ruta) Obtiene una instancia CollectionReference que hace referencia a una subcolección de reference en la ruta relativa especificada.
colección (referencia, ruta, segmentos de ruta) Obtiene una instancia CollectionReference que hace referencia a una subcolección de reference en la ruta relativa especificada.
eliminarDoc(referencia) Elimina el documento al que hace referencia la DocumentReference especificada.
doc(referencia, ruta, segmentos de ruta) Obtiene una instancia DocumentReference que hace referencia a un documento dentro de la reference en la ruta relativa especificada. Si no se especifica ninguna ruta, se utilizará una ID única generada automáticamente para la DocumentReference devuelta.
doc(referencia, ruta, segmentos de ruta) Obtiene una instancia DocumentReference que hace referencia a un documento dentro de la reference en la ruta relativa especificada.
getDoc(referencia) Lee el documento al que hace referencia este DocumentReference . Nota: getDoc() intenta proporcionar datos actualizados cuando es posible esperando datos del servidor, pero puede devolver datos almacenados en caché o fallar si no está conectado y no se puede acceder al servidor. Para especificar este comportamiento, invoque getDocFromCache() o getDocFromServer() .
getDocFromCache (referencia) Lee el documento al que hace referencia esta DocumentReference desde la memoria caché. Devuelve un error si el documento no está actualmente en caché.
getDocFromServer (referencia) Lee el documento al que hace referencia este DocumentReference desde el servidor. Devuelve un error si la red no está disponible.
onSnapshot (referencia, observador) Adjunta un detector para eventos DocumentSnapshot . Puede pasar devoluciones de llamada onNext y onError individuales o pasar un único objeto observador con devoluciones de llamada next y error . NOTA: Aunque se puede proporcionar una devolución de llamada onCompletion , nunca se llamará porque la secuencia de instantáneas es interminable.
onSnapshot(referencia, opciones, observador) Adjunta un detector para eventos DocumentSnapshot . Puede pasar devoluciones de llamada onNext y onError individuales o pasar un único objeto observador con devoluciones de llamada next y error . NOTA: Aunque se puede proporcionar una devolución de llamada onCompletion , nunca se llamará porque la secuencia de instantáneas es interminable.
onSnapshot(referencia, onNext, onError, onCompletion) Adjunta un detector para eventos DocumentSnapshot . Puede pasar devoluciones de llamada onNext y onError individuales o pasar un único objeto observador con devoluciones de llamada next y error . NOTA: Aunque se puede proporcionar una devolución de llamada onCompletion , nunca se llamará porque la secuencia de instantáneas es interminable.
onSnapshot(referencia, opciones, onNext, onError, onCompletion) Adjunta un detector para eventos DocumentSnapshot . Puede pasar devoluciones de llamada onNext y onError individuales o pasar un único objeto observador con devoluciones de llamada next y error . NOTA: Aunque se puede proporcionar una devolución de llamada onCompletion , nunca se llamará porque la secuencia de instantáneas es interminable.
setDoc(referencia, datos) Escribe en el documento al que hace referencia este DocumentReference . Si el documento aún no existe, se creará.
setDoc(referencia, datos, opciones) Escribe en el documento al que hace referencia la DocumentReference especificada. Si el documento aún no existe, se creará. Si proporciona merge o mergeFields , los datos proporcionados se pueden combinar en un documento existente.
updateDoc(referencia, datos) Actualiza los campos del documento al que hace referencia la DocumentReference especificada. La actualización fallará si se aplica a un documento que no existe.
updateDoc(referencia, campo, valor, másCamposAndValues) Actualiza los campos en el documento al que hace referencia la DocumentReference especificada. La actualización fallará si se aplica a un documento que no existe. Los campos anidados se pueden actualizar proporcionando cadenas de ruta de campo separadas por puntos o proporcionando objetos FieldPath .
función (configuración...)
memoriaLocalCache(configuración) Crea una instancia de MemoryLocalCache . La instancia se puede configurar en FirestoreSettings.cache para indicarle al SDK qué capa de caché usar.
memoriaLruGarbageCollector(configuración) Crea una instancia de MemoryLruGarbageCollector . Se puede especificar un tamaño de destino como parte del parámetro de configuración. El recopilador comenzará a eliminar documentos una vez que el tamaño de la caché supere el tamaño especificado. El tamaño de caché predeterminado es 40 MB (40 * 1024 * 1024 bytes).
persistenteLocalCache(configuración) Crea una instancia de PersistentLocalCache . La instancia se puede configurar en FirestoreSettings.cache para indicarle al SDK qué capa de caché usar. La caché persistente no se puede utilizar en un entorno Node.js.
persistenteSingleTabManager (configuración) Crea una instancia de PersistentSingleTabManager .
función (instantánea...)
finalizar en (instantánea) Crea un QueryEndAtConstraint que modifica el conjunto de resultados para que finalice en el documento proporcionado (inclusive). La posición final es relativa al orden de la consulta. El documento debe contener todos los campos proporcionados en el ordenPor de la consulta.
finalizar antes (instantánea) Crea un QueryEndAtConstraint que modifica el conjunto de resultados para que finalice antes del documento proporcionado (exclusivo). La posición final es relativa al orden de la consulta. El documento debe contener todos los campos proporcionados en el ordenPor de la consulta.
empezar después (instantánea) Crea un QueryStartAtConstraint que modifica el conjunto de resultados para que comience después del documento proporcionado (exclusivo). La posición inicial es relativa al orden de la consulta. El documento debe contener todos los campos proporcionados en el ordenPor de la consulta.
inicio en (instantánea) Crea un QueryStartAtConstraint que modifica el conjunto de resultados para comenzar en el documento proporcionado (inclusive). La posición inicial es relativa al orden de la consulta. El documento debe contener todos los campos proporcionados en el orderBy de esta consulta.

Clases

Clase Descripción
Campo agregado Representa una agregación que puede realizar Firestore.
Instantánea de consulta agregada Los resultados de la ejecución de una consulta de agregación.
bytes Un objeto inmutable que representa una matriz de bytes.
ColecciónReferencia Se puede utilizar un objeto CollectionReference para agregar documentos, obtener referencias de documentos y consultar documentos (usando query() ).
Referencia de documento Una DocumentReference se refiere a la ubicación de un documento en una base de datos de Firestore y se puede usar para escribir, leer o escuchar la ubicación. El documento en la ubicación referenciada puede existir o no.
Instantánea del documento Un DocumentSnapshot contiene datos leídos de un documento en su base de datos de Firestore. Los datos se pueden extraer con .data() o .get(<field>) para obtener un campo específico. Para una DocumentSnapshot que apunta a un documento no existente, cualquier acceso a datos devolverá "indefinido". Puede utilizar el método exists() para verificar explícitamente la existencia de un documento.
Ruta de campo Un FieldPath se refiere a un campo en un documento. La ruta puede consistir en un único nombre de campo (que hace referencia a un campo de nivel superior en el documento) o una lista de nombres de campos (que hace referencia a un campo anidado en el documento). Cree un FieldPath proporcionando nombres de campos. Si se proporciona más de un nombre de campo, la ruta apuntará a un campo anidado en un documento.
Valor de campo Valores centinela que se pueden utilizar al escribir campos de documentos con set() o update() .
Tienda de fuego La interfaz del servicio Cloud Firestore. No llame a este constructor directamente. En su lugar, utilice getFirestore() .
Error de tienda de fuego Un error devuelto por una operación de Firestore.
Geopunto Un objeto inmutable que representa una ubicación geográfica en Firestore. La ubicación se representa como un par de latitud/longitud. Los valores de latitud están en el rango de [-90, 90]. Los valores de longitud están en el rango de [-180, 180].
Tarea de paquete de carga Representa la tarea de cargar un paquete de Firestore. Proporciona el progreso de la carga del paquete, así como la finalización de tareas y eventos de error. La API es compatible con Promise<LoadBundleTaskProgress> .
Administrador de índice de caché persistente Un PersistentCacheIndexManager para configurar índices de caché persistentes utilizados para la ejecución de consultas locales. Para usarlo, llame getPersistentCacheIndexManager() para obtener una instancia.
Consulta Una Query se refiere a una consulta que puede leer o escuchar. También puede construir objetos Query refinados agregando filtros y ordenándolos.
QueryCompositeFilterConstraint Se utiliza un QueryCompositeFilterConstraint para limitar el conjunto de documentos devueltos por una consulta de Firestore realizando el OR o el AND lógico de múltiples QueryFieldFilterConstraint . s o QueryCompositeFilterConstraint s. QueryCompositeFilterConstraint se crean invocando or() o and() y luego se pueden pasar a query() para crear una nueva instancia de consulta que también contenga QueryCompositeFilterConstraint .
Restricción de consulta Se utiliza una QueryConstraint para limitar el conjunto de documentos devueltos por una consulta de Firestore. Los QueryConstraint se crean invocando dónde() , ordenar por() , empezar en() , empezar después() , finalizar antes() , finalizar en() , límite() , limitToLast() y luego se puede pasar a query() para crear una nueva instancia de consulta que también contenga este QueryConstraint .
ConsultaDocumentoInstantánea Un QueryDocumentSnapshot contiene datos leídos de un documento en su base de datos de Firestore como parte de una consulta. Se garantiza que el documento existe y sus datos se pueden extraer con .data() o .get(<field>) para obtener un campo específico. Un QueryDocumentSnapshot ofrece la misma superficie API que un DocumentSnapshot . Dado que los resultados de la consulta solo contienen documentos existentes, la propiedad exists siempre será verdadera y data() nunca devolverá "indefinido".
QueryEndAtConstraint Se utiliza QueryEndAtConstraint para excluir documentos del final de un conjunto de resultados devuelto por una consulta de Firestore. QueryEndAtConstraint se crean invocando endAt() o endBefore() y luego se pueden pasar a query() para crear una nueva instancia de consulta que también contenga este QueryEndAtConstraint .
Restricción de filtro de campo de consulta Un QueryFieldFilterConstraint se utiliza para limitar el conjunto de documentos devueltos por una consulta de Firestore filtrando uno o más campos de documento. QueryFieldFilterConstraint se crean invocando where() y luego se pueden pasar a query() para crear una nueva instancia de consulta que también contenga este QueryFieldFilterConstraint .
Restricción de límite de consulta Se utiliza un QueryLimitConstraint para limitar la cantidad de documentos devueltos por una consulta de Firestore. QueryLimitConstraint se crean invocando limit() o limitToLast() y luego se pueden pasar a query() para crear una nueva instancia de consulta que también contenga este QueryLimitConstraint .
ConsultaOrderByConstraint Se utiliza QueryOrderByConstraint para ordenar el conjunto de documentos devueltos por una consulta de Firestore. QueryOrderByConstraint s are created by invoking orderBy() and can then be passed to query() to create a new query instance that also contains this QueryOrderByConstraint . Note: Documents that do not contain the orderBy field will not be present in the query result.
QuerySnapshot A QuerySnapshot contains zero or more DocumentSnapshot objects representing the results of a query. The documents can be accessed as an array via the docs property or enumerated using the forEach method. The number of documents can be determined via the empty and size properties.
QueryStartAtConstraint 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 this QueryStartAtConstraint .
SnapshotMetadata Metadata about a snapshot, describing the state of the snapshot.
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, ie 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 .
Transaction A reference to a transaction. The Transaction object passed to a transaction's updateFunction provides the methods to read and write data within the transaction context. See runTransaction() .
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.

Interfaces

Interface Description
AggregateSpec Specifies a set of aggregations and their aliases.
DocumentChange A DocumentChange represents a change to the documents matching a query. It contains the document affected and the type of change that occurred.
DocumentData Document data (for use with setDoc() ) consists of fields mapped to values.
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 , and FirestoreSettings.experimentalLongPollingOptions .
FirestoreDataConverter Converter used by withConverter() to transform user objects of type AppModelType into Firestore data of type DbModelType . Using the converter allows you to specify generic type arguments when storing and retrieving objects from Firestore.
FirestoreSettings Specifies custom configurations for your Cloud Firestore instance. You must set these before invoking any other methods.
Index (BETA) The SDK definition of a Firestore index.
IndexConfiguration (BETA) A list of Firestore indexes to speed up local query execution. See JSON Format for a description of the format of the index definition.
IndexField (BETA) A single field element in an index configuration.
LoadBundleTaskProgress Represents a progress update or a final state from loading bundles.
MemoryCacheSettings An settings object to configure an MemoryLocalCache instance.
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.
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 call initializeFirestore using the settings object.
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.
PersistenceSettings Settings that can be passed to enableIndexedDbPersistence() to configure Firestore persistence. Persistence cannot be used in a Node.js environment.
PersistentCacheSettings An settings object to configure an PersistentLocalCache instance. Persistent cache cannot be used in a Node.js environment.
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 call initializeFirestore using the settings object.
PersistentMultipleTabManager A tab manager supporting multiple tabs. SDK will synchronize queries and mutations done across all tabs using the SDK.
PersistentSingleTabManager A tab manager supportting only one tab, no synchronization will be performed across tabs.
PersistentSingleTabManagerSettings Type to configure an PersistentSingleTabManager instance.
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.
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).
TransactionOptions Options to customize transaction behavior.
Unsubscribe A function returned by onSnapshot() that removes the listener when invoked.

Variables

Variable Description
CACHE_SIZE_UNLIMITED 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.

Type Aliases

Type Alias Description
AddPrefixToKeys Returns a new map where every key is prefixed with the outer key appended to a dot.
AggregateFieldType The union of all AggregateField types that are supported by Firestore.
AggregateSpecData A type whose keys are taken from an AggregateSpec , and whose values are the result of the aggregation performed by the corresponding AggregateField from the input AggregateSpec .
AggregateType Union type representing the aggregate type to be performed.
ChildUpdateFields 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 of T[K] on Record , since T[K] is evaluated as an expression and not distributed. See https://www.typescriptlang.org/docs/handbook/advanced-types.html#distributive-conditional-types
DocumentChangeType The type of a DocumentChange may be 'added', 'removed', or 'modified'.
FirestoreErrorCode 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 (eg 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.
FirestoreLocalCache Union type from all supported SDK cache layer.
MemoryGarbageCollector Union type from all support gabage collectors for memory local cache.
NestedUpdateFields For each field (eg 'bar'), find all nested keys (eg { 'bar.baz': T1, 'bar.qux': T2 } ). Intersect them together to make a single map containing all possible keys that are all marked as optional
OrderByDirection The direction of a orderBy() clause is specified as 'desc' or 'asc' (descending or ascending).
PartialWithFieldValue Similar to Typescript's Partial<T> , but allows nested fields to be omitted and FieldValues to be passed in as property values.
PersistentTabManager A union of all available tab managers.
Primitive Primitive types.
QueryConstraintType Describes the different query constraints available in this SDK.
QueryFilterConstraint QueryFilterConstraint is a helper union type that represents QueryFieldFilterConstraint and QueryCompositeFilterConstraint .
QueryNonFilterConstraint 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 the QueryConstraint .
SetOptions An options object that configures the behavior of 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 with merge: true .
TaskState 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.
UnionToIntersection 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
UpdateData Update data (for use with updateDoc() ) that consists of field paths (eg '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.
WhereFilterOp Filter conditions in a where() clause are specified using the strings '&lt;', '&lt;=', '==', '!=', '&gt;=', '&gt;', 'array-contains', 'in', 'array-contains-any', and 'not-in'.
WithFieldValue Allows FieldValues to be passed in as a property value while maintaining type safety.

getFirestore()

Returns the existing default Firestore instance that is associated with the provided FirebaseApp . If no instance exists, initializes a new instance with default settings.

Signature:

export declare function getFirestore(app: FirebaseApp): Firestore;

Parameters

Parameter Type Description
app FirebaseApp The FirebaseApp instance that the returned Firestore instance is associated with.

Returns:

Firestore

The default Firestore instance of the provided app.

getFirestore()

This API is provided as a preview for developers and may change based on feedback that we receive. Do not use this API in a production environment.

Returns the existing named Firestore instance that is associated with the provided FirebaseApp . If no instance exists, initializes a new instance with default settings.

Signature:

export declare function getFirestore(app: FirebaseApp, databaseId: string): Firestore;

Parameters

Parameter Type Description
app FirebaseApp The FirebaseApp instance that the returned Firestore instance is associated with.
databaseId string The name of the database.

Returns:

Firestore

The named Firestore instance of the provided app.

initializeFirestore()

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() .

Signature:

export declare function initializeFirestore(app: FirebaseApp, settings: FirestoreSettings, databaseId?: string): Firestore;

Parameters

Parameter Type Description
app FirebaseApp The FirebaseApp with which the Firestore instance will be associated.
settings FirestoreSettings A settings object to configure the Firestore instance.
databaseId string The name of the database.

Returns:

Firestore

A newly initialized Firestore instance.

clearIndexedDbPersistence()

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 .

Signature:

export declare function clearIndexedDbPersistence(firestore: Firestore): Promise<void>;

Parameters

Parameter Type Description
firestore Firestore The Firestore instance to clear persistence for.

Returns:

Promise<void>

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

collection()

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

Signature:

export declare function collection(firestore: Firestore, path: string, ...pathSegments: string[]): CollectionReference<DocumentData, DocumentData>;

Parameters

Parameter Type Description
firestore Firestore A reference to the root Firestore instance.
path string A slash-separated path to a collection.
pathSegments string[] Additional path segments to apply relative to the first argument.

Returns:

CollectionReference < DocumentData , DocumentData >

The CollectionReference instance.

Exceptions

If the final path has an even number of segments and does not point to a collection.

collectionGroup()

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

Signature:

export declare function collectionGroup(firestore: Firestore, collectionId: string): Query<DocumentData, DocumentData>;

Parameters

Parameter Type Description
firestore Firestore A reference to the root Firestore instance.
collectionId string Identifies the collections to query over. Every collection or subcollection with this ID as the last segment of its path will be included. Cannot contain a slash.

Returns:

Query < DocumentData , DocumentData >

The created Query .

connectFirestoreEmulator()

Modify this instance to communicate with the Cloud Firestore emulator.

Signature:

export declare function connectFirestoreEmulator(firestore: Firestore, host: string, port: number, options?: {
    mockUserToken?: EmulatorMockTokenOptions | string;
}): void;

Parameters

Parameter Type Description
firestore Firestore The Firestore instance to configure to connect to the emulator.
host string the emulator host (ex: localhost).
port number the emulator port (ex: 9000).
options { mockUserToken?: EmulatorMockTokenOptions | string; }

Returns:

void

disableNetwork()

Disables network usage for this instance. It can be re-enabled via enableNetwork() . While the network is disabled, any snapshot listeners, getDoc() or getDocs() calls will return results from cache, and any write operations will be queued until the network is restored.

Signature:

export declare function disableNetwork(firestore: Firestore): Promise<void>;

Parameters

Parameter Type Description
firestore Firestore

Returns:

Promise<void>

A Promise that is resolved once the network has been disabled.

doc()

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

Signature:

export declare function doc(firestore: Firestore, path: string, ...pathSegments: string[]): DocumentReference<DocumentData, DocumentData>;

Parameters

Parameter Type Description
firestore Firestore A reference to the root Firestore instance.
path string A slash-separated path to a document.
pathSegments string[] Additional path segments that will be applied relative to the first argument.

Returns:

DocumentReference < DocumentData , DocumentData >

The DocumentReference instance.

Exceptions

If the final path has an odd number of segments and does not point to a document.

enableIndexedDbPersistence()

This function will be removed in a future major release. Instead, set FirestoreSettings.localCache to an instance of PersistentLocalCache to turn on IndexedDb cache. Calling this function when FirestoreSettings.localCache is already specified will throw an exception.

Attempts to enable persistent storage, if possible.

Must be called before any other functions (other than initializeFirestore() , getFirestore() or clearIndexedDbPersistence() .

If this fails, enableIndexedDbPersistence() will reject the promise it returns. Note that even after this failure, the Firestore instance will remain usable, however offline persistence will be disabled.

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

* failed-precondition: The app is already open in another browser tab. * unimplemented: The browser is incompatible with the offline persistence implementation.

Persistence cannot be used in a Node.js environment.

Signature:

export declare function enableIndexedDbPersistence(firestore: Firestore, persistenceSettings?: PersistenceSettings): Promise<void>;

Parameters

Parameter Type Description
firestore Firestore The Firestore instance to enable persistence for.
persistenceSettings PersistenceSettings Optional settings object to configure persistence.

Returns:

Promise<void>

A Promise that represents successfully enabling persistent storage.

enableMultiTabIndexedDbPersistence()

This function will be removed in a future major release. Instead, set FirestoreSettings.localCache to an instance of PersistentLocalCache to turn on indexeddb cache. Calling this function when FirestoreSettings.localCache is already specified will throw an exception.

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.

If this fails, enableMultiTabIndexedDbPersistence() will reject the promise it returns. Note that even after this failure, the Firestore instance will remain usable, however offline persistence will be disabled.

There are several reasons why this can fail, which can be identified by the code 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.

Signature:

export declare function enableMultiTabIndexedDbPersistence(firestore: Firestore): Promise<void>;

Parameters

Parameter Type Description
firestore Firestore The Firestore instance to enable persistence for.

Returns:

Promise<void>

A Promise that represents successfully enabling persistent storage.

enableNetwork()

Re-enables use of the network for this Firestore instance after a prior call to disableNetwork() .

Signature:

export declare function enableNetwork(firestore: Firestore): Promise<void>;

Parameters

Parameter Type Description
firestore Firestore

Returns:

Promise<void>

A Promise that is resolved once the network has been enabled.

getPersistentCacheIndexManager()

Returns the PersistentCache Index Manager used by the given Firestore object.

The PersistentCacheIndexManager instance, or null if local persistent storage is not in use.

Signature:

export declare function getPersistentCacheIndexManager(firestore: Firestore): PersistentCacheIndexManager | null;

Parameters

Parameter Type Description
firestore Firestore

Returns:

PersistentCacheIndexManager | null

loadBundle()

Loads a Firestore bundle into the local cache.

Signature:

export declare function loadBundle(firestore: Firestore, bundleData: ReadableStream<Uint8Array> | ArrayBuffer | string): LoadBundleTask;

Parameters

Parameter Type Description
firestore Firestore The Firestore instance to load bundles for.
bundleData ReadableStream<Uint8Array> | ArrayBuffer | string An object representing the bundle to be loaded. Valid objects are ArrayBuffer , ReadableStream<Uint8Array> or string .

Returns:

LoadBundleTask

A LoadBundleTask object, which notifies callers with progress updates, and completion or error events. It can be used as a Promise<LoadBundleTaskProgress> .

namedQuery()

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.

Signature:

export declare function namedQuery(firestore: Firestore, name: string): Promise<Query | null>;

Parameters

Parameter Type Description
firestore Firestore The Firestore instance to read the query from.
name string The name of the query.

Returns:

Promise< Query | null>

A Promise that is resolved with the Query or null .

onSnapshotsInSync()

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.

Signature:

export declare function onSnapshotsInSync(firestore: Firestore, observer: {
    next?: (value: void) => void;
    error?: (error: FirestoreError) => void;
    complete?: () => void;
}): Unsubscribe;

Parameters

Parameter Type Description
firestore Firestore The instance of Firestore for synchronizing snapshots.
observer { next?: (value: void) => void; error?: (error: FirestoreError ) => void; complete?: () => void; } A single object containing next and error callbacks.

Returns:

Unsubscribe

An unsubscribe function that can be called to cancel the snapshot listener.

onSnapshotsInSync()

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.

Signature:

export declare function onSnapshotsInSync(firestore: Firestore, onSync: () => void): Unsubscribe;

Parameters

Parameter Type Description
firestore Firestore The Firestore instance for synchronizing snapshots.
onSync () => void A callback to be called every time all snapshot listeners are in sync with each other.

Returns:

Unsubscribe

An unsubscribe function that can be called to cancel the snapshot listener.

runTransaction()

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 the updateFunction . If it fails to commit after 5 attempts, the transaction fails.

The maximum number of writes allowed in a single transaction is 500.

Signature:

export declare function runTransaction<T>(firestore: Firestore, updateFunction: (transaction: Transaction) => Promise<T>, options?: TransactionOptions): Promise<T>;

Parameters

Parameter Type Description
firestore Firestore A reference to the Firestore database to run this transaction against.
updateFunction (transaction: Transaction ) => Promise<T> The function to execute within the transaction context.
options TransactionOptions An options object to configure maximum number of attempts to commit.

Returns:

Promise<T>

If the transaction completed successfully or was explicitly aborted (the updateFunction returned a failed promise), the promise returned by the updateFunction is returned here. Otherwise, if the transaction failed, a rejected promise with the corresponding failure error is returned.

setIndexConfiguration()

This API is provided as a preview for developers and may change based on feedback that we receive. Do not use this API in a production environment.

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. If IndexedDb is not enabled, any index configuration is ignored.

Signature:

export declare function setIndexConfiguration(firestore: Firestore, configuration: IndexConfiguration): Promise<void>;

Parameters

Parameter Type Description
firestore Firestore The Firestore instance to configure indexes for.
configuration IndexConfiguration The index definition.

Returns:

Promise<void>

A Promise that resolves once all indices are successfully configured.

Exceptions

FirestoreError if the JSON format is invalid.

setIndexConfiguration()

This API is provided as a preview for developers and may change based on feedback that we receive. Do not use this API in a production environment.

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() or enableMultiTabIndexedDbPersistence() 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.

Signature:

export declare function setIndexConfiguration(firestore: Firestore, json: string): Promise<void>;

Parameters

Parameter Type Description
firestore Firestore The Firestore instance to configure indexes for.
json string The JSON format exported by the Firebase CLI.

Returns:

Promise<void>

A Promise that resolves once all indices are successfully configured.

Exceptions

FirestoreError if the JSON format is invalid.

terminate()

Terminates the provided Firestore instance.

After calling terminate() only the clearIndexedDbPersistence() function may be used. Any other function will throw a FirestoreError .

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.

Signature:

export declare function terminate(firestore: Firestore): Promise<void>;

Parameters

Parameter Type Description
firestore Firestore

Returns:

Promise<void>

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

waitForPendingWrites()

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.

Signature:

export declare function waitForPendingWrites(firestore: Firestore): Promise<void>;

Parameters

Parameter Type Description
firestore Firestore

Returns:

Promise<void>

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

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.

Signature:

export declare function writeBatch(firestore: Firestore): WriteBatch;

Parameters

Parameter Type Description
firestore Firestore

Returns:

WriteBatch

A WriteBatch that can be used to atomically execute multiple writes.

count()

Create an AggregateField object that can be used to compute the count of documents in the result set of a query.

Signature:

export declare function count(): AggregateField<number>;

Returns:

AggregateField <number>

deleteField()

Returns a sentinel for use with updateDoc() or setDoc() with {merge: true} to mark a field for deletion.

Signature:

export declare function deleteField(): FieldValue;

Returns:

FieldValue

documentId()

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.

Signature:

export declare function documentId(): FieldPath;

Returns:

FieldPath

getFirestore()

Returns the existing default Firestore instance that is associated with the default FirebaseApp . If no instance exists, initializes a new instance with default settings.

Signature:

export declare function getFirestore(): Firestore;

Returns:

Firestore

The default Firestore instance of the default app.

memoryEagerGarbageCollector()

Creates an instance of MemoryEagerGarbageCollector . This is also the default garbage collector unless it is explicitly specified otherwise.

Signature:

export declare function memoryEagerGarbageCollector(): MemoryEagerGarbageCollector;

Returns:

MemoryEagerGarbageCollector

persistentMultipleTabManager()

Creates an instance of PersistentMultipleTabManager .

Signature:

export declare function persistentMultipleTabManager(): PersistentMultipleTabManager;

Returns:

PersistentMultipleTabManager

serverTimestamp()

Returns a sentinel used with setDoc() or updateDoc() to include a server-generated timestamp in the written data.

Signature:

export declare function serverTimestamp(): FieldValue;

Returns:

FieldValue

getFirestore()

This API is provided as a preview for developers and may change based on feedback that we receive. Do not use this API in a production environment.

Returns the existing named Firestore instance that is associated with the default FirebaseApp . If no instance exists, initializes a new instance with default settings.

Signature:

export declare function getFirestore(databaseId: string): Firestore;

Parameters

Parameter Type Description
databaseId string The name of the database.

Returns:

Firestore

The named Firestore instance of the default app.

arrayRemove()

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.

Signature:

export declare function arrayRemove(...elements: unknown[]): FieldValue;

Parameters

Parameter Type Description
elements unknown[] The elements to remove from the array.

Returns:

FieldValue

The FieldValue sentinel for use in a call to setDoc() or updateDoc()

arrayUnion()

Returns a special value that can be used with setDoc() or 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.

Signature:

export declare function arrayUnion(...elements: unknown[]): FieldValue;

Parameters

Parameter Type Description
elements unknown[] The elements to union into the array.

Returns:

FieldValue

The FieldValue sentinel for use in a call to setDoc() or updateDoc() .

average()

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.

Signature:

export declare function average(field: string | FieldPath): AggregateField<number | null>;

Parameters

Parameter Type Description
field string | FieldPath Specifies the field to average across the result set.

Returns:

AggregateField <number | null>

sum()

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.

Signature:

export declare function sum(field: string | FieldPath): AggregateField<number>;

Parameters

Parameter Type Description
field string | FieldPath Specifies the field to sum across the result set.

Returns:

AggregateField <number>

orderBy()

Creates a QueryOrderByConstraint that sorts the query result by the specified field, optionally in descending order instead of ascending.

Signature:

export declare function orderBy(fieldPath: string | FieldPath, directionStr?: OrderByDirection): QueryOrderByConstraint;

Parameters

Parameter Type Description
fieldPath string | FieldPath The field to sort by.
directionStr OrderByDirection Optional direction to sort by ('asc' or 'desc'). If not specified, order will be ascending.

Returns:

QueryOrderByConstraint

The created QueryOrderByConstraint .

where()

Creates a QueryFieldFilterConstraint that enforces that documents must contain the specified field and that the value should satisfy the relation constraint provided.

Signature:

export declare function where(fieldPath: string | FieldPath, opStr: WhereFilterOp, value: unknown): QueryFieldFilterConstraint;

Parameters

Parameter Type Description
fieldPath string | FieldPath The path to compare
opStr WhereFilterOp The operation string (eg "&lt;", "&lt;=", "==", "&lt;", "&lt;=", "!=").
value unknown The value for comparison

Returns:

QueryFieldFilterConstraint

The created QueryFieldFilterConstraint .

endAt()

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.

Signature:

export declare function endAt(...fieldValues: unknown[]): QueryEndAtConstraint;

Parameters

Parameter Type Description
fieldValues unknown[] The field values to end this query at, in order of the query's order by.

Returns:

QueryEndAtConstraint

A QueryEndAtConstraint to pass to query()

endBefore()

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.

Signature:

export declare function endBefore(...fieldValues: unknown[]): QueryEndAtConstraint;

Parameters

Parameter Type Description
fieldValues unknown[] The field values to end this query before, in order of the query's order by.

Returns:

QueryEndAtConstraint

A QueryEndAtConstraint to pass to query()

startAfter()

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.

Signature:

export declare function startAfter(...fieldValues: unknown[]): QueryStartAtConstraint;

Parameters

Parameter Type Description
fieldValues unknown[] The field values to start this query after, in order of the query's order by.

Returns:

QueryStartAtConstraint

A QueryStartAtConstraint to pass to query()

startAt()

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.

Signature:

export declare function startAt(...fieldValues: unknown[]): QueryStartAtConstraint;

Parameters

Parameter Type Description
fieldValues unknown[] The field values to start this query at, in order of the query's order by.

Returns:

QueryStartAtConstraint

A QueryStartAtConstraint to pass to query() .

deleteAllPersistentCacheIndexes()

Removes all persistent cache indexes.

Please note this function will also deletes indexes generated by setIndexConfiguration() , which is deprecated.

Signature:

export declare function deleteAllPersistentCacheIndexes(indexManager: PersistentCacheIndexManager): void;

Parameters

Parameter Type Description
indexManager PersistentCacheIndexManager

Returns:

void

disablePersistentCacheIndexAutoCreation()

Stops creating persistent cache indexes automatically for local query execution. The indexes which have been created by calling enablePersistentCacheIndexAutoCreation() still take effect.

Signature:

export declare function disablePersistentCacheIndexAutoCreation(indexManager: PersistentCacheIndexManager): void;

Parameters

Parameter Type Description
indexManager PersistentCacheIndexManager

Returns:

void

enablePersistentCacheIndexAutoCreation()

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.

Signature:

export declare function enablePersistentCacheIndexAutoCreation(indexManager: PersistentCacheIndexManager): void;

Parameters

Parameter Type Description
indexManager PersistentCacheIndexManager

Returns:

void

aggregateFieldEqual()

Compares two 'AggregateField ` instances for equality.

Signature:

export declare function aggregateFieldEqual(left: AggregateField<unknown>, right: AggregateField<unknown>): boolean;

Parameters

Parameter Type Description
left AggregateField <unknown> Compare this AggregateField to the right .
right AggregateField <unknown> Compare this AggregateField to the left .

Returns:

boolean

aggregateQuerySnapshotEqual()

Compares two AggregateQuerySnapshot instances for equality.

Two AggregateQuerySnapshot instances are considered "equal" if they have underlying queries that compare equal, and the same data.

Signature:

export declare function aggregateQuerySnapshotEqual<AggregateSpecType extends AggregateSpec, AppModelType, DbModelType extends DocumentData>(left: AggregateQuerySnapshot<AggregateSpecType, AppModelType, DbModelType>, right: AggregateQuerySnapshot<AggregateSpecType, AppModelType, DbModelType>): boolean;

Parameters

Parameter Type Description
left AggregateQuerySnapshot <AggregateSpecType, AppModelType, DbModelType> The first AggregateQuerySnapshot to compare.
right AggregateQuerySnapshot <AggregateSpecType, AppModelType, DbModelType> The second AggregateQuerySnapshot to compare.

Returns:

boolean

true if the objects are "equal", as defined above, or false otherwise.

queryEqual()

Returns true if the provided queries point to the same collection and apply the same constraints.

Signature:

export declare function queryEqual<AppModelType, DbModelType extends DocumentData>(left: Query<AppModelType, DbModelType>, right: Query<AppModelType, DbModelType>): boolean;

Parameters

Parameter Type Description
left Query <AppModelType, DbModelType> A Query to compare.
right Query <AppModelType, DbModelType> A Query to compare.

Returns:

boolean

true if the references point to the same location in the same Firestore database.

refEqual()

Returns true if the provided references are equal.

Signature:

export declare function refEqual<AppModelType, DbModelType extends DocumentData>(left: DocumentReference<AppModelType, DbModelType> | CollectionReference<AppModelType, DbModelType>, right: DocumentReference<AppModelType, DbModelType> | CollectionReference<AppModelType, DbModelType>): boolean;

Parameters

Parameter Type Description
left DocumentReference <AppModelType, DbModelType> | CollectionReference <AppModelType, DbModelType> A reference to compare.
right DocumentReference <AppModelType, DbModelType> | CollectionReference <AppModelType, DbModelType> A reference to compare.

Returns:

boolean

true if the references point to the same location in the same Firestore database.

snapshotEqual()

Returns true if the provided snapshots are equal.

Signature:

export declare function snapshotEqual<AppModelType, DbModelType extends DocumentData>(left: DocumentSnapshot<AppModelType, DbModelType> | QuerySnapshot<AppModelType, DbModelType>, right: DocumentSnapshot<AppModelType, DbModelType> | QuerySnapshot<AppModelType, DbModelType>): boolean;

Parameters

Parameter Type Description
left DocumentSnapshot <AppModelType, DbModelType> | QuerySnapshot <AppModelType, DbModelType> A snapshot to compare.
right DocumentSnapshot <AppModelType, DbModelType> | QuerySnapshot <AppModelType, DbModelType> A snapshot to compare.

Returns:

boolean

true if the snapshots are equal.

limit()

Creates a QueryLimitConstraint that only returns the first matching documents.

Signature:

export declare function limit(limit: number): QueryLimitConstraint;

Parameters

Parameter Type Description
limit number The maximum number of items to return.

Returns:

QueryLimitConstraint

The created QueryLimitConstraint .

limitToLast()

Creates a QueryLimitConstraint that only returns the last matching documents.

You must specify at least one orderBy clause for limitToLast queries, otherwise an exception will be thrown during execution.

Signature:

export declare function limitToLast(limit: number): QueryLimitConstraint;

Parameters

Parameter Type Description
limit number The maximum number of items to return.

Returns:

QueryLimitConstraint

The created QueryLimitConstraint .

setLogLevel()

Sets the verbosity of Cloud Firestore logs (debug, error, or silent).

Signature:

export declare function setLogLevel(logLevel: LogLevel): void;

Parameters

Parameter Type Description
logLevel 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.

Returns:

void

increment()

Returns a special value that can be used with setDoc() or 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 to Number.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.

Signature:

export declare function increment(n: number): FieldValue;

Parameters

Parameter Type Description
n number The value to increment by.

Returns:

FieldValue

The FieldValue sentinel for use in a call to setDoc() or updateDoc()

getAggregateFromServer()

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 even perform aggregations of the documents if the result set would be prohibitively large to download entirely (eg 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 request using this source necessarily involves a round trip to the server.

Signature:

export declare function getAggregateFromServer<AggregateSpecType extends AggregateSpec, AppModelType, DbModelType extends DocumentData>(query: Query<AppModelType, DbModelType>, aggregateSpec: AggregateSpecType): Promise<AggregateQuerySnapshot<AggregateSpecType, AppModelType, DbModelType>>;

Parameters

Parameter Type Description
query Query <AppModelType, DbModelType> The query whose result set to aggregate over.
aggregateSpec AggregateSpecType 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.

Returns:

Promise< AggregateQuerySnapshot <AggregateSpecType, AppModelType, DbModelType>>

Example

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;

getCountFromServer()

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 even count the documents if the result set would be prohibitively large to download entirely (eg 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 request using this source necessarily involves a round trip to the server.

Signature:

export declare function getCountFromServer<AppModelType, DbModelType extends DocumentData>(query: Query<AppModelType, DbModelType>): Promise<AggregateQuerySnapshot<{
    count: AggregateField<number>;
}, AppModelType, DbModelType>>;

Parameters

Parameter Type Description
query Query <AppModelType, DbModelType> The query whose result set size to calculate.

Returns:

Promise< AggregateQuerySnapshot <{ count: AggregateField <number>; }, AppModelType, DbModelType>>

A Promise that will be resolved with the count; the count can be retrieved from snapshot.data().count , where snapshot is the AggregateQuerySnapshot to which the returned Promise resolves.

getDocs()

Executes the query and returns the results as a QuerySnapshot .

Signature:

export declare function getDocs<AppModelType, DbModelType extends DocumentData>(query: Query<AppModelType, DbModelType>): Promise<QuerySnapshot<AppModelType, DbModelType>>;

Parameters

Parameter Type Description
query Query <AppModelType, DbModelType>

Returns:

Promise< QuerySnapshot <AppModelType, DbModelType>>

A Promise that will be resolved with the results of the query.

getDocsFromCache()

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.

Signature:

export declare function getDocsFromCache<AppModelType, DbModelType extends DocumentData>(query: Query<AppModelType, DbModelType>): Promise<QuerySnapshot<AppModelType, DbModelType>>;

Parameters

Parameter Type Description
query Query <AppModelType, DbModelType>

Returns:

Promise< QuerySnapshot <AppModelType, DbModelType>>

A Promise that will be resolved with the results of the query.

getDocsFromServer()

Executes the query and returns the results as a QuerySnapshot from the server. Returns an error if the network is not available.

Signature:

export declare function getDocsFromServer<AppModelType, DbModelType extends DocumentData>(query: Query<AppModelType, DbModelType>): Promise<QuerySnapshot<AppModelType, DbModelType>>;

Parameters

Parameter Type Description
query Query <AppModelType, DbModelType>

Returns:

Promise< QuerySnapshot <AppModelType, DbModelType>>

A Promise that will be resolved with the results of the query.

onSnapshot()

Attaches a listener for QuerySnapshot events. You may either pass individual onNext and onError callbacks or pass a single observer object with next and error callbacks. The listener can be cancelled by calling the function that is returned when onSnapshot is called.

NOTE: Although an onCompletion callback can be provided, it will never be called because the snapshot stream is never-ending.

Signature:

export declare function onSnapshot<AppModelType, DbModelType extends DocumentData>(query: Query<AppModelType, DbModelType>, observer: {
    next?: (snapshot: QuerySnapshot<AppModelType, DbModelType>) => void;
    error?: (error: FirestoreError) => void;
    complete?: () => void;
}): Unsubscribe;

Parameters

Parameter Type Description
query Query <AppModelType, DbModelType> The query to listen to.
observer { next?: (snapshot: QuerySnapshot <AppModelType, DbModelType>) => void; error?: (error: FirestoreError ) => void; complete?: () => void; } A single object containing next and error callbacks.

Returns:

Unsubscribe

An unsubscribe function that can be called to cancel the snapshot listener.

onSnapshot()

Attaches a listener for QuerySnapshot events. You may either pass individual onNext and onError callbacks or pass a single observer object with next and error callbacks. The listener can be cancelled by calling the function that is returned when onSnapshot is called.

NOTE: Although an onCompletion callback can be provided, it will never be called because the snapshot stream is never-ending.

Signature:

export declare function onSnapshot<AppModelType, DbModelType extends DocumentData>(query: Query<AppModelType, DbModelType>, options: SnapshotListenOptions, observer: {
    next?: (snapshot: QuerySnapshot<AppModelType, DbModelType>) => void;
    error?: (error: FirestoreError) => void;
    complete?: () => void;
}): Unsubscribe;

Parameters

Parameter Type Description
query Query <AppModelType, DbModelType> The query to listen to.
options SnapshotListenOptions Options controlling the listen behavior.
observer { next?: (snapshot: QuerySnapshot <AppModelType, DbModelType>) => void; error?: (error: FirestoreError ) => void; complete?: () => void; } A single object containing next and error callbacks.

Returns:

Unsubscribe

An unsubscribe function that can be called to cancel the snapshot listener.

onSnapshot()

Attaches a listener for QuerySnapshot events. You may either pass individual onNext and onError callbacks or pass a single observer object with next and error callbacks. The listener can be cancelled by calling the function that is returned when onSnapshot is called.

NOTE: Although an onCompletion callback can be provided, it will never be called because the snapshot stream is never-ending.

Signature:

export declare function onSnapshot<AppModelType, DbModelType extends DocumentData>(query: Query<AppModelType, DbModelType>, onNext: (snapshot: QuerySnapshot<AppModelType, DbModelType>) => void, onError?: (error: FirestoreError) => void, onCompletion?: () => void): Unsubscribe;

Parameters

Parameter Type Description
query Query <AppModelType, DbModelType> The query to listen to.
onNext (snapshot: QuerySnapshot <AppModelType, DbModelType>) => void A callback to be called every time a new QuerySnapshot is available.
onError (error: FirestoreError ) => void A callback to be called if the listen fails or is cancelled. No further callbacks will occur.
onCompletion () => void Can be provided, but will not be called since streams are never ending.

Returns:

Unsubscribe

An unsubscribe function that can be called to cancel the snapshot listener.

onSnapshot()

Attaches a listener for QuerySnapshot events. You may either pass individual onNext and onError callbacks or pass a single observer object with next and error callbacks. The listener can be cancelled by calling the function that is returned when onSnapshot is called.

NOTE: Although an onCompletion callback can be provided, it will never be called because the snapshot stream is never-ending.

Signature:

export declare function onSnapshot<AppModelType, DbModelType extends DocumentData>(query: Query<AppModelType, DbModelType>, options: SnapshotListenOptions, onNext: (snapshot: QuerySnapshot<AppModelType, DbModelType>) => void, onError?: (error: FirestoreError) => void, onCompletion?: () => void): Unsubscribe;

Parameters

Parameter Type Description
query Query <AppModelType, DbModelType> The query to listen to.
options SnapshotListenOptions Options controlling the listen behavior.
onNext (snapshot: QuerySnapshot <AppModelType, DbModelType>) => void A callback to be called every time a new QuerySnapshot is available.
onError (error: FirestoreError ) => void A callback to be called if the listen fails or is cancelled. No further callbacks will occur.
onCompletion () => void Can be provided, but will not be called since streams are never ending.

Returns:

Unsubscribe

An unsubscribe function that can be called to cancel the snapshot listener.

query()

Creates a new immutable instance of Query that is extended to also include additional query constraints.

Signature:

export declare function query<AppModelType, DbModelType extends DocumentData>(query: Query<AppModelType, DbModelType>, compositeFilter: QueryCompositeFilterConstraint, ...queryConstraints: QueryNonFilterConstraint[]): Query<AppModelType, DbModelType>;

Parameters

Parameter Type Description
query Query <AppModelType, DbModelType> The Query instance to use as a base for the new constraints.
compositeFilter QueryCompositeFilterConstraint The QueryCompositeFilterConstraint to apply. Create QueryCompositeFilterConstraint using and() or or() .
queryConstraints QueryNonFilterConstraint [] Additional QueryNonFilterConstraint s to apply (eg orderBy() , limit() ).

Returns:

Query <AppModelType, DbModelType>

Exceptions

if any of the provided query constraints cannot be combined with the existing or new constraints.

query()

Creates a new immutable instance of Query that is extended to also include additional query constraints.

Signature:

export declare function query<AppModelType, DbModelType extends DocumentData>(query: Query<AppModelType, DbModelType>, ...queryConstraints: QueryConstraint[]): Query<AppModelType, DbModelType>;

Parameters

Parameter Type Description
query Query <AppModelType, DbModelType> The Query instance to use as a base for the new constraints.
queryConstraints QueryConstraint [] The list of QueryConstraint s to apply.

Returns:

Query <AppModelType, DbModelType>

Exceptions

if any of the provided query constraints cannot be combined with the existing or new constraints.

and()

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.

Signature:

export declare function and(...queryConstraints: QueryFilterConstraint[]): QueryCompositeFilterConstraint;

Parameters

Parameter Type Description
queryConstraints QueryFilterConstraint [] Optional. The list of QueryFilterConstraint s to perform a conjunction for. These must be created with calls to where() , or() , or and() .

Returns:

QueryCompositeFilterConstraint

The newly created QueryCompositeFilterConstraint .

or()

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.

Signature:

export declare function or(...queryConstraints: QueryFilterConstraint[]): QueryCompositeFilterConstraint;

Parameters

Parameter Type Description
queryConstraints QueryFilterConstraint [] Optional. The list of QueryFilterConstraint s to perform a disjunction for. These must be created with calls to where() , or() , or and() .

Returns:

QueryCompositeFilterConstraint

The newly created QueryCompositeFilterConstraint .

addDoc()

Add a new document to specified CollectionReference with the given data, assigning it a document ID automatically.

Signature:

export declare function addDoc<AppModelType, DbModelType extends DocumentData>(reference: CollectionReference<AppModelType, DbModelType>, data: WithFieldValue<AppModelType>): Promise<DocumentReference<AppModelType, DbModelType>>;

Parameters

Parameter Type Description
reference CollectionReference <AppModelType, DbModelType> A reference to the collection to add this document to.
data WithFieldValue <AppModelType> An Object containing the data for the new document.

Returns:

Promise< DocumentReference <AppModelType, DbModelType>>

A Promise resolved with a DocumentReference pointing to the newly created document after it has been written to the backend (Note that it won't resolve while you're offline).

collection()

Gets a CollectionReference instance that refers to a subcollection of reference at the the specified relative path.

Signature:

export declare function collection<AppModelType, DbModelType extends DocumentData>(reference: CollectionReference<AppModelType, DbModelType>, path: string, ...pathSegments: string[]): CollectionReference<DocumentData, DocumentData>;

Parameters

Parameter Type Description
reference CollectionReference <AppModelType, DbModelType> A reference to a collection.
path string A slash-separated path to a collection.
pathSegments string[] Additional path segments to apply relative to the first argument.

Returns:

CollectionReference < DocumentData , DocumentData >

The CollectionReference instance.

Exceptions

If the final path has an even number of segments and does not point to a collection.

collection()

Gets a CollectionReference instance that refers to a subcollection of reference at the the specified relative path.

Signature:

export declare function collection<AppModelType, DbModelType extends DocumentData>(reference: DocumentReference<AppModelType, DbModelType>, path: string, ...pathSegments: string[]): CollectionReference<DocumentData, DocumentData>;

Parameters

Parameter Type Description
reference DocumentReference <AppModelType, DbModelType> A reference to a Firestore document.
path string A slash-separated path to a collection.
pathSegments string[] Additional path segments that will be applied relative to the first argument.

Returns:

CollectionReference < DocumentData , DocumentData >

The CollectionReference instance.

Exceptions

If the final path has an even number of segments and does not point to a collection.

deleteDoc()

Deletes the document referred to by the specified DocumentReference .

Signature:

export declare function deleteDoc<AppModelType, DbModelType extends DocumentData>(reference: DocumentReference<AppModelType, DbModelType>): Promise<void>;

Parameters

Parameter Type Description
reference DocumentReference <AppModelType, DbModelType> A reference to the document to delete.

Returns:

Promise<void>

A Promise resolved once the document has been successfully deleted from the backend (note that it won't resolve while you're offline).

doc()

Gets a DocumentReference instance that refers to a document within reference at the specified relative path. If no path is specified, an automatically-generated unique ID will be used for the returned DocumentReference .

Signature:

export declare function doc<AppModelType, DbModelType extends DocumentData>(reference: CollectionReference<AppModelType, DbModelType>, path?: string, ...pathSegments: string[]): DocumentReference<AppModelType, DbModelType>;

Parameters

Parameter Type Description
reference CollectionReference <AppModelType, DbModelType> A reference to a collection.
path string A slash-separated path to a document. Has to be omitted to use auto-genrated IDs.
pathSegments string[] Additional path segments that will be applied relative to the first argument.

Returns:

DocumentReference <AppModelType, DbModelType>

The DocumentReference instance.

Exceptions

If the final path has an odd number of segments and does not point to a document.

doc()

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

Signature:

export declare function doc<AppModelType, DbModelType extends DocumentData>(reference: DocumentReference<AppModelType, DbModelType>, path: string, ...pathSegments: string[]): DocumentReference<DocumentData, DocumentData>;

Parameters

Parameter Type Description
reference DocumentReference <AppModelType, DbModelType> A reference to a Firestore document.
path string A slash-separated path to a document.
pathSegments string[] Additional path segments that will be applied relative to the first argument.

Returns:

DocumentReference < DocumentData , DocumentData >

The DocumentReference instance.

Exceptions

If the final path has an odd number of segments and does not point to a document.

getDoc()

Reads the document referred to by this DocumentReference .

Signature:

export declare function getDoc<AppModelType, DbModelType extends DocumentData>(reference: DocumentReference<AppModelType, DbModelType>): Promise<DocumentSnapshot<AppModelType, DbModelType>>;

Parameters

Parameter Type Description
reference DocumentReference <AppModelType, DbModelType> The reference of the document to fetch.

Returns:

Promise< DocumentSnapshot <AppModelType, DbModelType>>

A Promise resolved with a DocumentSnapshot containing the current document contents.

getDocFromCache()

Reads the document referred to by this DocumentReference from cache. Returns an error if the document is not currently cached.

Signature:

export declare function getDocFromCache<AppModelType, DbModelType extends DocumentData>(reference: DocumentReference<AppModelType, DbModelType>): Promise<DocumentSnapshot<AppModelType, DbModelType>>;

Parameters

Parameter Type Description
reference DocumentReference <AppModelType, DbModelType>

Returns:

Promise< DocumentSnapshot <AppModelType, DbModelType>>

A Promise resolved with a DocumentSnapshot containing the current document contents.

getDocFromServer()

Reads the document referred to by this DocumentReference from the server. Returns an error if the network is not available.

Signature:

export declare function getDocFromServer<AppModelType, DbModelType extends DocumentData>(reference: DocumentReference<AppModelType, DbModelType>): Promise<DocumentSnapshot<AppModelType, DbModelType>>;

Parameters

Parameter Type Description
reference DocumentReference <AppModelType, DbModelType>

Returns:

Promise< DocumentSnapshot <AppModelType, DbModelType>>

A Promise resolved with a DocumentSnapshot containing the current document contents.

onSnapshot()

Attaches a listener for DocumentSnapshot events. You may either pass individual onNext and onError callbacks or pass a single observer object with next and error callbacks.

NOTE: Although an onCompletion callback can be provided, it will never be called because the snapshot stream is never-ending.

Signature:

export declare function onSnapshot<AppModelType, DbModelType extends DocumentData>(reference: DocumentReference<AppModelType, DbModelType>, observer: {
    next?: (snapshot: DocumentSnapshot<AppModelType, DbModelType>) => void;
    error?: (error: FirestoreError) => void;
    complete?: () => void;
}): Unsubscribe;

Parameters

Parameter Type Description
reference DocumentReference <AppModelType, DbModelType> A reference to the document to listen to.
observer { next?: (snapshot: DocumentSnapshot <AppModelType, DbModelType>) => void; error?: (error: FirestoreError ) => void; complete?: () => void; } A single object containing next and error callbacks.

Returns:

Unsubscribe

An unsubscribe function that can be called to cancel the snapshot listener.

onSnapshot()

Attaches a listener for DocumentSnapshot events. You may either pass individual onNext and onError callbacks or pass a single observer object with next and error callbacks.

NOTE: Although an onCompletion callback can be provided, it will never be called because the snapshot stream is never-ending.

Signature:

export declare function onSnapshot<AppModelType, DbModelType extends DocumentData>(reference: DocumentReference<AppModelType, DbModelType>, options: SnapshotListenOptions, observer: {
    next?: (snapshot: DocumentSnapshot<AppModelType, DbModelType>) => void;
    error?: (error: FirestoreError) => void;
    complete?: () => void;
}): Unsubscribe;

Parameters

Parameter Type Description
reference DocumentReference <AppModelType, DbModelType> A reference to the document to listen to.
options SnapshotListenOptions Options controlling the listen behavior.
observer { next?: (snapshot: DocumentSnapshot <AppModelType, DbModelType>) => void; error?: (error: FirestoreError ) => void; complete?: () => void; } A single object containing next and error callbacks.

Returns:

Unsubscribe

An unsubscribe function that can be called to cancel the snapshot listener.

onSnapshot()

Attaches a listener for DocumentSnapshot events. You may either pass individual onNext and onError callbacks or pass a single observer object with next and error callbacks.

NOTE: Although an onCompletion callback can be provided, it will never be called because the snapshot stream is never-ending.

Signature:

export declare function onSnapshot<AppModelType, DbModelType extends DocumentData>(reference: DocumentReference<AppModelType, DbModelType>, onNext: (snapshot: DocumentSnapshot<AppModelType, DbModelType>) => void, onError?: (error: FirestoreError) => void, onCompletion?: () => void): Unsubscribe;

Parameters

Parameter Type Description
reference DocumentReference <AppModelType, DbModelType> A reference to the document to listen to.
onNext (snapshot: DocumentSnapshot <AppModelType, DbModelType>) => void A callback to be called every time a new DocumentSnapshot is available.
onError (error: FirestoreError ) => void A callback to be called if the listen fails or is cancelled. No further callbacks will occur.
onCompletion () => void Can be provided, but will not be called since streams are never ending.

Returns:

Unsubscribe

An unsubscribe function that can be called to cancel the snapshot listener.

onSnapshot()

Attaches a listener for DocumentSnapshot events. You may either pass individual onNext and onError callbacks or pass a single observer object with next and error callbacks.

NOTE: Although an onCompletion callback can be provided, it will never be called because the snapshot stream is never-ending.

Signature:

export declare function onSnapshot<AppModelType, DbModelType extends DocumentData>(reference: DocumentReference<AppModelType, DbModelType>, options: SnapshotListenOptions, onNext: (snapshot: DocumentSnapshot<AppModelType, DbModelType>) => void, onError?: (error: FirestoreError) => void, onCompletion?: () => void): Unsubscribe;

Parameters

Parameter Type Description
reference DocumentReference <AppModelType, DbModelType> A reference to the document to listen to.
options SnapshotListenOptions Options controlling the listen behavior.
onNext (snapshot: DocumentSnapshot <AppModelType, DbModelType>) => void A callback to be called every time a new DocumentSnapshot is available.
onError (error: FirestoreError ) => void A callback to be called if the listen fails or is cancelled. No further callbacks will occur.
onCompletion () => void Can be provided, but will not be called since streams are never ending.

Returns:

Unsubscribe

An unsubscribe function that can be called to cancel the snapshot listener.

setDoc()

Writes to the document referred to by this DocumentReference . If the document does not yet exist, it will be created.

Signature:

export declare function setDoc<AppModelType, DbModelType extends DocumentData>(reference: DocumentReference<AppModelType, DbModelType>, data: WithFieldValue<AppModelType>): Promise<void>;

Parameters

Parameter Type Description
reference DocumentReference <AppModelType, DbModelType> A reference to the document to write.
data WithFieldValue <AppModelType> A map of the fields and values for the document.

Returns:

Promise<void>

A Promise resolved once the data has been successfully written to the backend (note that it won't resolve while you're offline).

setDoc()

Writes to the document referred to by the specified DocumentReference . If the document does not yet exist, it will be created. If you provide merge or mergeFields , the provided data can be merged into an existing document.

Signature:

export declare function setDoc<AppModelType, DbModelType extends DocumentData>(reference: DocumentReference<AppModelType, DbModelType>, data: PartialWithFieldValue<AppModelType>, options: SetOptions): Promise<void>;

Parameters

Parameter Type Description
reference DocumentReference <AppModelType, DbModelType> A reference to the document to write.
data PartialWithFieldValue <AppModelType> A map of the fields and values for the document.
options SetOptions An object to configure the set behavior.

Returns:

Promise<void>

A Promise resolved once the data has been successfully written to the backend (note that it won't resolve while you're offline).

updateDoc()

Updates fields in the document referred to by the specified DocumentReference . The update will fail if applied to a document that does not exist.

Signature:

export declare function updateDoc<AppModelType, DbModelType extends DocumentData>(reference: DocumentReference<AppModelType, DbModelType>, data: UpdateData<DbModelType>): Promise<void>;

Parameters

Parameter Type Description
reference DocumentReference <AppModelType, DbModelType> A reference to the document to update.
data UpdateData <DbModelType> 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:

Promise<void>

A Promise resolved once the data has been successfully written to the backend (note that it won't resolve while you're offline).

updateDoc()

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.

Signature:

export declare function updateDoc<AppModelType, DbModelType extends DocumentData>(reference: DocumentReference<AppModelType, DbModelType>, field: string | FieldPath, value: unknown, ...moreFieldsAndValues: unknown[]): Promise<void>;

Parameters

Parameter Type Description
reference DocumentReference <AppModelType, DbModelType> A reference to the document to update.
field string | FieldPath The first field to update.
value unknown The first value.
moreFieldsAndValues unknown[] Additional key value pairs.

Returns:

Promise<void>

A Promise resolved once the data has been successfully written to the backend (note that it won't resolve while you're offline).

memoryLocalCache()

Creates an instance of MemoryLocalCache . The instance can be set to FirestoreSettings.cache to tell the SDK which cache layer to use.

Signature:

export declare function memoryLocalCache(settings?: MemoryCacheSettings): MemoryLocalCache;

Parameters

Parameter Type Description
settings MemoryCacheSettings

Returns:

MemoryLocalCache

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).

Signature:

export declare function memoryLruGarbageCollector(settings?: {
    cacheSizeBytes?: number;
}): MemoryLruGarbageCollector;

Parameters

Parameter Type Description
settings { cacheSizeBytes?: number; }

Returns:

MemoryLruGarbageCollector

persistentLocalCache()

Creates an instance of PersistentLocalCache . The instance can be set to FirestoreSettings.cache to tell the SDK which cache layer to use.

Persistent cache cannot be used in a Node.js environment.

Signature:

export declare function persistentLocalCache(settings?: PersistentCacheSettings): PersistentLocalCache;

Parameters

Parameter Type Description
settings PersistentCacheSettings

Returns:

PersistentLocalCache

persistentSingleTabManager()

Creates an instance of PersistentSingleTabManager .

Signature:

export declare function persistentSingleTabManager(settings: PersistentSingleTabManagerSettings | undefined): PersistentSingleTabManager;

Parameters

Parameter Type Description
settings PersistentSingleTabManagerSettings | undefined Configures the created tab manager.

Returns:

PersistentSingleTabManager

endAt()

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.

Signature:

export declare function endAt<AppModelType, DbModelType extends DocumentData>(snapshot: DocumentSnapshot<AppModelType, DbModelType>): QueryEndAtConstraint;

Parameters

Parameter Type Description
snapshot DocumentSnapshot <AppModelType, DbModelType> The snapshot of the document to end at.

Returns:

QueryEndAtConstraint

A QueryEndAtConstraint to pass to query()

endBefore()

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.

Signature:

export declare function endBefore<AppModelType, DbModelType extends DocumentData>(snapshot: DocumentSnapshot<AppModelType, DbModelType>): QueryEndAtConstraint;

Parameters

Parameter Type Description
snapshot DocumentSnapshot <AppModelType, DbModelType> The snapshot of the document to end before.

Returns:

QueryEndAtConstraint

A QueryEndAtConstraint to pass to query()

startAfter()

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.

Signature:

export declare function startAfter<AppModelType, DbModelType extends DocumentData>(snapshot: DocumentSnapshot<AppModelType, DbModelType>): QueryStartAtConstraint;

Parameters

Parameter Type Description
snapshot DocumentSnapshot <AppModelType, DbModelType> The snapshot of the document to start after.

Returns:

QueryStartAtConstraint

A QueryStartAtConstraint to pass to query()

startAt()

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.

Signature:

export declare function startAt<AppModelType, DbModelType extends DocumentData>(snapshot: DocumentSnapshot<AppModelType, DbModelType>): QueryStartAtConstraint;

Parameters

Parameter Type Description
snapshot DocumentSnapshot <AppModelType, DbModelType> The snapshot of the document to start at.

Returns:

QueryStartAtConstraint

A QueryStartAtConstraint to pass to query() .

CACHE_SIZE_UNLIMITED

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.

Signature:

CACHE_SIZE_UNLIMITED = -1

AddPrefixToKeys

Returns a new map where every key is prefixed with the outer key appended to a dot.

Signature:

export declare type AddPrefixToKeys<Prefix extends string, T extends Record<string, unknown>> = {
    [K in keyof T & string as `${Prefix}.${K}`]+?: string extends K ? any : T[K];
};

AggregateFieldType

The union of all AggregateField types that are supported by Firestore.

Signature:

export declare type AggregateFieldType = ReturnType<typeof sum> | ReturnType<typeof average> | ReturnType<typeof count>;

AggregateSpecData

A type whose keys are taken from an AggregateSpec , and whose values are the result of the aggregation performed by the corresponding AggregateField from the input AggregateSpec .

Signature:

export declare type AggregateSpecData<T extends AggregateSpec> = {
    [P in keyof T]: T[P] extends AggregateField<infer U> ? U : never;
};

AggregateType

Union type representing the aggregate type to be performed.

Signature:

export declare type AggregateType = 'count' | 'avg' | 'sum';

ChildUpdateFields

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 of T[K] on Record , since T[K] is evaluated as an expression and not distributed.

See https://www.typescriptlang.org/docs/handbook/advanced-types.html#distributive-conditional-types

Signature:

export declare type ChildUpdateFields<K extends string, V> = V extends Record<string, unknown> ? AddPrefixToKeys<K, UpdateData<V>> : never;

DocumentChangeType

The type of a DocumentChange may be 'added', 'removed', or 'modified'.

Signature:

export declare type DocumentChangeType = 'added' | 'removed' | 'modified';

FirestoreErrorCode

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 (eg 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.

Signature:

export declare 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';

FirestoreLocalCache

Union type from all supported SDK cache layer.

Signature:

export declare type FirestoreLocalCache = MemoryLocalCache | PersistentLocalCache;

MemoryGarbageCollector

Union type from all support gabage collectors for memory local cache.

Signature:

export declare type MemoryGarbageCollector = MemoryEagerGarbageCollector | MemoryLruGarbageCollector;

NestedUpdateFields

For each field (eg 'bar'), find all nested keys (eg { 'bar.baz': T1, 'bar.qux': T2 } ). Intersect them together to make a single map containing all possible keys that are all marked as optional

Signature:

export declare type NestedUpdateFields<T extends Record<string, unknown>> = UnionToIntersection<{
    [K in keyof T & string]: ChildUpdateFields<K, T[K]>;
}[keyof T & string]>;

OrderByDirection

The direction of a orderBy() clause is specified as 'desc' or 'asc' (descending or ascending).

Signature:

export declare type OrderByDirection = 'desc' | 'asc';

PartialWithFieldValue

Similar to Typescript's Partial<T> , but allows nested fields to be omitted and FieldValues to be passed in as property values.

Signature:

export declare type PartialWithFieldValue<T> = Partial<T> | (T extends Primitive ? T : T extends {} ? {
    [K in keyof T]?: PartialWithFieldValue<T[K]> | FieldValue;
} : never);

PersistentTabManager

A union of all available tab managers.

Signature:

export declare type PersistentTabManager = PersistentSingleTabManager | PersistentMultipleTabManager;

Primitive

Primitive types.

Signature:

export declare type Primitive = string | number | boolean | undefined | null;

QueryConstraintType

Describes the different query constraints available in this SDK.

Signature:

export declare type QueryConstraintType = 'where' | 'orderBy' | 'limit' | 'limitToLast' | 'startAt' | 'startAfter' | 'endAt' | 'endBefore';

QueryFilterConstraint

QueryFilterConstraint is a helper union type that represents QueryFieldFilterConstraint and QueryCompositeFilterConstraint .

Signature:

export declare type QueryFilterConstraint = QueryFieldFilterConstraint | QueryCompositeFilterConstraint;

QueryNonFilterConstraint

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 the QueryConstraint .

Signature:

export declare type QueryNonFilterConstraint = QueryOrderByConstraint | QueryLimitConstraint | QueryStartAtConstraint | QueryEndAtConstraint;

SetOptions

An options object that configures the behavior of 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 with merge: true .

Signature:

export declare type SetOptions = {
    readonly merge?: boolean;
} | {
    readonly mergeFields?: Array<string | FieldPath>;
};

TaskState

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.

Signature:

export declare type TaskState = 'Error' | 'Running' | 'Success';

UnionToIntersection

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

Signature:

export declare type UnionToIntersection<U> = (U extends unknown ? (k: U) => void : never) extends (k: infer I) => void ? I : never;

UpdateData

Update data (for use with updateDoc() ) that consists of field paths (eg '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.

Signature:

export declare type UpdateData<T> = T extends Primitive ? T : T extends {} ? {
    [K in keyof T]?: UpdateData<T[K]> | FieldValue;
} & NestedUpdateFields<T> : Partial<T>;

WhereFilterOp

Filter conditions in a where() clause are specified using the strings '&lt;', '&lt;=', '==', '!=', '&gt;=', '&gt;', 'array-contains', 'in', 'array-contains-any', and 'not-in'.

Signature:

export declare type WhereFilterOp = '<' | '<=' | '==' | '!=' | '>=' | '>' | 'array-contains' | 'in' | 'array-contains-any' | 'not-in';

WithFieldValue

Allows FieldValues to be passed in as a property value while maintaining type safety.

Signature:

export declare type WithFieldValue<T> = T | (T extends Primitive ? T : T extends {} ? {
    [K in keyof T]: WithFieldValue<T[K]> | FieldValue;
} : never);