@firebase/firestore/lite

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 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) Inicializa una nueva instancia de Cloud 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() .
inicializarFirestore(aplicación, configuración, ID de base de datos) (BETA) Inicializa una nueva instancia de Cloud 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...)
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 que están 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.
doc(firestore, ruta, segmentos de ruta) Obtiene una instancia DocumentReference que hace referencia al documento en la ruta absoluta especificada.
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.
terminar (firestore) Termina la instancia Firestore proporcionada. Después de llamar terminate() solo se pueden utilizar las funciones clearIndexedDbPersistence() . Cualquier otra función arrojará un FirestoreError . La terminación no cancela ninguna escritura pendiente y ninguna promesa que esté esperando una respuesta del servidor no se resolverá. Para reiniciar después de la terminación, cree una nueva instancia de Firestore con getFirestore() . 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.
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. El resultado de estas escrituras solo se reflejará en las lecturas de documentos que se produzcan después de que se resuelva la promesa devuelta. Si el cliente está desconectado, la escritura falla. Si desea ver modificaciones locales o escrituras en búfer hasta que el cliente esté en línea, use el SDK de Firestore completo.
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.
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 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 (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...)
getAggregate(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).
getCount(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).
obtenerDocs(consulta) Ejecuta la consulta y devuelve los resultados como QuerySnapshot. . Todas las consultas son ejecutadas directamente por el servidor, incluso si la consulta se ejecutó previamente. Las modificaciones recientes solo se reflejan en los resultados recuperados si ya han sido aplicadas por el backend. Si el cliente está desconectado, la operación falla. Para ver los resultados previamente almacenados en caché y las modificaciones locales, use el SDK completo de Firestore.
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. El resultado de esta escritura solo se reflejará en las lecturas de documentos que se produzcan después de que se resuelva la promesa devuelta. Si el cliente está desconectado, la escritura falla. Si desea ver modificaciones locales o escrituras en búfer hasta que el cliente esté en línea, use el SDK de Firestore completo.
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. La eliminación solo se reflejará en las lecturas de documentos que se produzcan después de que se resuelva la promesa devuelta. Si el cliente está desconectado, la eliminación falla. Si desea ver modificaciones locales o escrituras en búfer hasta que el cliente esté en línea, use el SDK de Firestore completo.
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 la referencia del documento especificado. Todos los documentos se obtienen directamente del servidor, incluso si el documento se leyó o modificó previamente. Las modificaciones recientes solo se reflejan en la DocumentSnapshot recuperada si ya han sido aplicadas por el backend. Si el cliente está desconectado, la lectura falla. Si desea utilizar el almacenamiento en caché o ver modificaciones locales, utilice el SDK completo de Firestore.
setDoc(referencia, datos) Escribe en el documento al que hace referencia la DocumentReference especificada. Si el documento aún no existe, se creará. El resultado de esta escritura solo se reflejará en las lecturas de documentos que se produzcan después de que se resuelva la promesa devuelta. Si el cliente está desconectado, la escritura falla. Si desea ver modificaciones locales o escrituras en búfer hasta que el cliente esté en línea, use el SDK de Firestore completo.
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. El resultado de esta escritura solo se reflejará en las lecturas de documentos que se produzcan después de que se resuelva la promesa devuelta. Si el cliente está desconectado, la escritura falla. Si desea ver modificaciones locales o escrituras en búfer hasta que el cliente esté en línea, use el SDK de Firestore completo.
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. El resultado de esta actualización solo se reflejará en las lecturas de documentos que se produzcan después de que se resuelva la promesa devuelta. Si el cliente está desconectado, la actualización falla. Si desea ver modificaciones locales o escrituras en búfer hasta que el cliente esté en línea, use el SDK de Firestore completo.
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 . El resultado de esta actualización solo se reflejará en las lecturas de documentos que se produzcan después de que se resuelva la promesa devuelta. Si el cliente está desconectado, la actualización falla. Si desea ver modificaciones locales o escrituras en búfer hasta que el cliente esté en línea, use el SDK de Firestore completo.
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].
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 se crean invocando orderBy() y luego se pueden pasar a query() para crear una nueva instancia de consulta que también contenga este QueryOrderByConstraint . Nota: Los documentos que no contengan el campo ordenarPor no estarán presentes en el resultado de la consulta.
ConsultaInstantánea Un QuerySnapshot contiene cero o más objetos DocumentSnapshot que representan los resultados de una consulta. Se puede acceder a los documentos como una matriz a través de la propiedad docs o enumerarlos usando el método forEach . El número de documentos se puede determinar mediante las propiedades empty y size .
ConsultaInicioEnConstraint Se utiliza QueryStartAtConstraint para excluir documentos del inicio de un conjunto de resultados devuelto por una consulta de Firestore. QueryStartAtConstraint se crean invocando startAt() o startAfter() y luego se pueden pasar a query() para crear una nueva instancia de consulta que también contenga este QueryStartAtConstraint .
Marca de tiempo Una Timestamp representa un punto en el tiempo independiente de cualquier zona horaria o calendario, representado como segundos y fracciones de segundos con una resolución de nanosegundos en la época UTC. Está codificado utilizando el Calendario Gregoriano Proléptico que extiende el calendario gregoriano hacia atrás hasta el año uno. Se codifica asumiendo que todos los minutos tienen una duración de 60 segundos, es decir, los segundos intercalares están "borrados" de modo que no se necesita una tabla de segundos intercalares para la interpretación. El rango es de 0001-01-01T00:00:00Z a 9999-12-31T23:59:59.999999999Z. Para obtener ejemplos y especificaciones adicionales, consulte la definición de marca de tiempo. .
Transacción Una referencia a una transacción. El objeto Transaction pasado a la updateFunction de una transacción proporciona los métodos para leer y escribir datos dentro del contexto de la transacción. Ver ejecutarTransacción() .
escribir lote Un lote de escritura, utilizado para realizar múltiples escrituras como una sola unidad atómica. Se puede adquirir un objeto WriteBatch llamando a writeBatch() . Proporciona métodos para agregar escrituras al lote de escritura. Ninguna de las escrituras se confirmará (ni será visible localmente) hasta que se llame a WriteBatch.commit() .

Interfaces

Interfaz Descripción
Especificaciones agregadas Especifica un conjunto de agregaciones y sus alias.
Datos del documento Datos del documento (para usar con setDoc() ) consta de campos asignados a valores.
FirestoreDataConverter Convertidor utilizado por withConverter() para transformar objetos de usuario de tipo AppModelType en datos de Firestore de tipo DbModelType . El uso del convertidor le permite especificar argumentos de tipo genérico al almacenar y recuperar objetos de Firestore.
Ajustes Especifica configuraciones personalizadas para su instancia de Cloud Firestore. Debe configurarlos antes de invocar cualquier otro método.
Opciones de transacción Opciones para personalizar el comportamiento de las transacciones.

Tipo de alias

Tipo Alias Descripción
AgregarPrefijoAClaves Devuelve un nuevo mapa donde cada clave tiene como prefijo la clave exterior adjunta a un punto.
Tipo de campo agregado La unión de todos los tipos AggregateField admitidos por Firestore.
Datos de especificación agregados Un tipo cuyas claves se toman de AggregateSpec y cuyos valores son el resultado de la agregación realizada por el AggregateField correspondiente a partir de la entrada AggregateSpec .
Tipo agregado Tipo de unión que representa el tipo de agregado que se va a realizar.
Campos de actualización infantil Ayudante para calcular los campos anidados para un tipo determinado T1. Esto es necesario para distribuir tipos de unión como undefined | {...} (sucede con accesorios opcionales) o {a: A} | {b: B} . En este caso de uso, V se usa para distribuir los tipos de unión de T[K] en Record , ya que T[K] se evalúa como una expresión y no se distribuye. Consulte https://www.typescriptlang.org/docs/handbook/advanced-types.html#distributive-conditional-types
Código de error de Firestore El conjunto de códigos de estado de Firestore. Los códigos son los mismos que los expuestos por gRPC aquí: https://github.com/grpc/grpc/blob/master/doc/statuscodes.md Valores posibles: - 'cancelado': la operación fue cancelada (normalmente por la persona que llama). - 'desconocido': error desconocido o error de un dominio de error diferente. - 'argumento-inválido': el cliente especificó un argumento no válido. Tenga en cuenta que esto difiere de la "condición previa fallida". 'argumento-inválido' indica argumentos que son problemáticos independientemente del estado del sistema (por ejemplo, un nombre de campo no válido). - 'fecha límite excedida': la fecha límite expiró antes de que se pudiera completar la operación. Para operaciones que cambian el estado del sistema, este error puede aparecer incluso si la operación se completó exitosamente. Por ejemplo, una respuesta exitosa de un servidor podría haberse retrasado lo suficiente como para que expirara el plazo. - 'no encontrado': No se encontró algún documento solicitado. - 'ya-existe': Algún documento que intentamos crear ya existe. - 'permiso denegado': la persona que llama no tiene permiso para ejecutar la operación especificada. - 'recursos agotados': se ha agotado algún recurso, tal vez una cuota por usuario, o tal vez todo el sistema de archivos se haya quedado sin espacio. - 'precondición fallida': La operación fue rechazada porque el sistema no se encuentra en el estado requerido para la ejecución de la operación. - 'abortada': la operación fue abortada, generalmente debido a un problema de concurrencia como transacciones abortadas, etc. - 'fuera de rango': la operación se intentó más allá del rango válido. - 'no implementado': la operación no está implementada o no es compatible/habilitada. - 'interno': Errores internos. Significa que se han roto algunas invariantes esperadas por el sistema subyacente. Si ve uno de estos errores, algo está muy roto. - 'no disponible': el servicio no está disponible actualmente. Lo más probable es que se trate de una condición transitoria y se puede corregir volviendo a intentarlo con un retroceso. - 'pérdida de datos': pérdida o corrupción de datos irrecuperables. - 'no autenticado': La solicitud no tiene credenciales de autenticación válidas para la operación.
Campos de actualización anidados Para cada campo (por ejemplo, 'barra'), busque todas las claves anidadas (por ejemplo, { 'bar.baz': T1, 'bar.qux': T2 } ). Interséctalos para crear un único mapa que contenga todas las claves posibles, todas marcadas como opcionales.
Ordenarpordirección La dirección de una cláusula orderBy() se especifica como 'desc' o 'asc' (descendente o ascendente).
ParcialConValorDeCampo Similar a Partial<T> de Typecript, pero permite omitir campos anidados y pasar FieldValues ​​como valores de propiedad.
Primitivo Tipos primitivos.
Tipo de restricción de consulta Describe las diferentes restricciones de consulta disponibles en este SDK.
Restricción de filtro de consulta QueryFilterConstraint es un tipo de unión auxiliar que representa QueryFieldFilterConstraint y QueryCompositeFilterConstraint . .
QueryNonFilterConstraint QueryNonFilterConstraint es un tipo de unión auxiliar que representa QueryConstraints que se utilizan para limitar u ordenar el conjunto de documentos, pero que no filtran explícitamente en un campo de documento. Los QueryNonFilterConstraint se crean invocando orderBy() , empezar en() , empezar después() , finalizar antes() , finalizar en() , limit() o limitToLast() y luego se puede pasar a query() para crear una nueva instancia de consulta que también contenga QueryConstraint .
Establecer opciones Un objeto de opciones que configura el comportamiento de setDoc() y llamadas. Estas llamadas se pueden configurar para realizar fusiones granulares en lugar de sobrescribir los documentos de destino en su totalidad proporcionando SetOptions con merge: true .
unión a la intersección Dado un tipo de unión U = T1 | T2 | ... , devuelve un tipo intersectado (T1 & T2 & ...) . Utiliza tipos condicionales distributivos e inferencias a partir de tipos condicionales. Esto funciona porque varios candidatos para el mismo tipo de variable en posiciones contravariantes hacen que se infiera un tipo de intersección. https://www.typescriptlang.org/docs/handbook/advanced-types.html#type-inference-in-conditional-types https://stackoverflow.com/questions/50374908/transform-union-type-to-intersection -tipo
Actualizar datos Actualizar datos (para usar con updateDoc() ) que consta de rutas de campo (por ejemplo, 'foo' o 'foo.baz') asignadas a valores. Los campos que contienen puntos hacen referencia a campos anidados dentro del documento. Los FieldValues ​​se pueden pasar como valores de propiedad.
DondeFilterOp Las condiciones de filtro en una cláusula where() se especifican usando las cadenas '&lt;', '&lt;=', '==', '!=', '&gt;=', '&gt;', 'array-contains' , 'en', 'matriz-contiene-cualquiera' y 'no-en'.
Con valor de campo Permite pasar FieldValues ​​como un valor de propiedad manteniendo la seguridad de tipos.

obtenerFirestore()

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.

Firma:

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

Parámetros

Parámetro Tipo Descripción
aplicación Aplicación Firebase La instancia de FirebaseApp a la que está asociada la instancia de Firestore devuelta.

Devoluciones:

Tienda de fuego

La instancia de Firestore de la aplicación proporcionada.

obtenerFirestore()

Esta API se proporciona como una vista previa para los desarrolladores y puede cambiar según los comentarios que recibamos. No utilice esta API en un entorno de producción.

Devuelve la instancia de Firestore existente que está asociada con la FirebaseApp proporcionada. . Si no existe ninguna instancia, inicializa una nueva instancia con la configuración predeterminada.

Firma:

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

Parámetros

Parámetro Tipo Descripción
aplicación Aplicación Firebase La instancia de FirebaseApp a la que está asociada la instancia de Firestore devuelta.
ID de base de datos cadena El nombre de la base de datos.

Devoluciones:

Tienda de fuego

La instancia de Firestore de la aplicación proporcionada.

inicializarFirestore()

Inicializa una nueva instancia de Cloud 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() .

Firma:

export declare function initializeFirestore(app: FirebaseApp, settings: Settings): Firestore;

Parámetros

Parámetro Tipo Descripción
aplicación Aplicación Firebase La FirebaseApp con la que se asociará la instancia Firestore .
ajustes Ajustes Un objeto de configuración para configurar la instancia Firestore .

Devoluciones:

Tienda de fuego

Una instancia Firestore recién inicializada.

inicializarFirestore()

Esta API se proporciona como una vista previa para los desarrolladores y puede cambiar según los comentarios que recibamos. No utilice esta API en un entorno de producción.

Inicializa una nueva instancia de Cloud 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() .

Firma:

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

Parámetros

Parámetro Tipo Descripción
aplicación Aplicación Firebase La FirebaseApp con la que se asociará la instancia Firestore .
ajustes Ajustes Un objeto de configuración para configurar la instancia Firestore .
ID de base de datos cadena El nombre de la base de datos.

Devoluciones:

Tienda de fuego

Una instancia Firestore recién inicializada.

recopilación()

Obtiene una instancia CollectionReference que hace referencia a la colección en la ruta absoluta especificada.

Firma:

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

Parámetros

Parámetro Tipo Descripción
tienda de fuego Tienda de fuego Una referencia a la instancia raíz Firestore .
camino cadena Una ruta de acceso a una colección separada por barras diagonales.
rutaSegmentos cadena[] Segmentos de ruta adicionales para aplicar en relación con el primer argumento.

Devoluciones:

ColecciónReferencia < DocumentoDatos , Datos del documento >

La instancia CollectionReference .

Excepciones

Si el camino final tiene un número par de segmentos y no apunta a una colección.

grupocolección()

Crea y devuelve una nueva instancia Query que incluye todos los documentos de la base de datos que están contenidos en una colección o subcolección con el collectionId dado. .

Firma:

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

Parámetros

Parámetro Tipo Descripción
tienda de fuego Tienda de fuego Una referencia a la instancia raíz Firestore .
ID de colección cadena Identifica las colecciones sobre las que consultar. Se incluirá cada colección o subcolección con este ID como último segmento de su ruta. No puede contener una barra.

Devoluciones:

Consulta < 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

Parámetro Tipo 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

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

Parámetro Tipo 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.

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

Parámetro Tipo 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.

terminate()

Terminates the provided Firestore instance.

After calling terminate() only the clearIndexedDbPersistence() functions may be used. Any other function will throw a FirestoreError . Termination does not cancel any pending writes, and any promises that are awaiting a response from the server will not be resolved.

To restart after termination, create a new instance of Firestore with getFirestore() .

Signature:

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

Parameters

Parámetro Tipo Description
firestore Firestore The Firestore instance to terminate.

Returns:

Promise<void>

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

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.

The result of these writes will only be reflected in document reads that occur after the returned promise resolves. If the client is offline, the write fails. If you would like to see local modifications or buffer writes until the client is online, use the full Firestore SDK.

Signature:

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

Parameters

Parámetro Tipo 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 Firestore instance of the provided app.

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

Parámetro Tipo Description
databaseId string The name of the database.

Returns:

Firestore

The Firestore instance of the provided 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

Parámetro Tipo 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

Parámetro Tipo 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

Parámetro Tipo 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

Parámetro Tipo 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

Parámetro Tipo 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

Parámetro Tipo 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

Parámetro Tipo 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

Parámetro Tipo 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

Parámetro Tipo 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

Parámetro Tipo 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() .

aggregateFieldEqual()

Compares two 'AggregateField ` instances for equality.

Signature:

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

Parameters

Parámetro Tipo 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

Parámetro Tipo 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

Parámetro Tipo 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

Parámetro Tipo 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

Parámetro Tipo 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

Parámetro Tipo 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

Parámetro Tipo 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

Parámetro Tipo 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

Parámetro Tipo Description
n number The value to increment by.

Returns:

FieldValue

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

getAggregate()

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

Signature:

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

Parameters

Parámetro Tipo 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 getAggregate(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;

getCount()

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

Signature:

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

Parameters

Parámetro Tipo 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 .

All queries are executed directly by the server, even if the the query was previously executed. Recent modifications are only reflected in the retrieved results if they have already been applied by the backend. If the client is offline, the operation fails. To see previously cached result and local modifications, use the full Firestore SDK.

Signature:

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

Parameters

Parámetro Tipo Description
query Query <AppModelType, DbModelType> The Query to execute.

Returns:

Promise< QuerySnapshot <AppModelType, DbModelType>>

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

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

Parámetro Tipo 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

Parámetro Tipo 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

Parámetro Tipo 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

Parámetro Tipo 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.

The result of this write will only be reflected in document reads that occur after the returned promise resolves. If the client is offline, the write fails. If you would like to see local modifications or buffer writes until the client is online, use the full Firestore SDK.

Signature:

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

Parameters

Parámetro Tipo 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.

Exceptions

Error - If the provided input is not a valid Firestore document.

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

Parámetro Tipo 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

Parámetro Tipo 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 .

The deletion will only be reflected in document reads that occur after the returned promise resolves. If the client is offline, the delete fails. If you would like to see local modifications or buffer writes until the client is online, use the full Firestore SDK.

Signature:

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

Parameters

Parámetro Tipo 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.

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

Parámetro Tipo 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

Parámetro Tipo 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 the specified document reference.

All documents are directly fetched from the server, even if the document was previously read or modified. Recent modifications are only reflected in the retrieved DocumentSnapshot if they have already been applied by the backend. If the client is offline, the read fails. If you like to use caching or see local modifications, please use the full Firestore SDK.

Signature:

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

Parameters

Parámetro Tipo 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.

setDoc()

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

The result of this write will only be reflected in document reads that occur after the returned promise resolves. If the client is offline, the write fails. If you would like to see local modifications or buffer writes until the client is online, use the full Firestore SDK.

Signature:

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

Parameters

Parámetro Tipo 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.

Exceptions

Error - If the provided input is not a valid Firestore document.

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.

The result of this write will only be reflected in document reads that occur after the returned promise resolves. If the client is offline, the write fails. If you would like to see local modifications or buffer writes until the client is online, use the full Firestore SDK.

Signature:

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

Parameters

Parámetro Tipo 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.

Exceptions

Error - If the provided input is not a valid Firestore document.

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.

The result of this update will only be reflected in document reads that occur after the returned promise resolves. If the client is offline, the update fails. If you would like to see local modifications or buffer writes until the client is online, use the full Firestore SDK.

Signature:

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

Parameters

Parámetro Tipo 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.

Exceptions

Error - If the provided input is not valid Firestore data.

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.

The result of this update will only be reflected in document reads that occur after the returned promise resolves. If the client is offline, the update fails. If you would like to see local modifications or buffer writes until the client is online, use the full Firestore SDK.

Signature:

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

Parameters

Parámetro Tipo 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.

Exceptions

Error - If the provided input is not valid Firestore data.

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

Parámetro Tipo 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

Parámetro Tipo 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

Parámetro Tipo 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

Parámetro Tipo Description
snapshot DocumentSnapshot <AppModelType, DbModelType> The snapshot of the document to start at.

Returns:

QueryStartAtConstraint

A QueryStartAtConstraint to pass to query() .

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;

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

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

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>;
};

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