Funções
Função | Descrição |
---|---|
função (aplicativo...) | |
obterFirestore(aplicativo) | Retorna a instância padrão existente do Firestore associada ao FirebaseApp fornecido . Se não existir nenhuma instância, inicializa uma nova instância com configurações padrão. |
getFirestore(aplicativo,databaseId) | (BETA) Retorna a instância nomeada existente do Firestore associada ao FirebaseApp fornecido . Se não existir nenhuma instância, inicializa uma nova instância com configurações padrão. |
inicializeFirestore(aplicativo, configurações, ID do banco de dados) | Inicializa uma nova instância do Firestore com as configurações fornecidas. Só pode ser chamado antes de qualquer outra função, incluindo getFirestore() . Se as configurações personalizadas estiverem vazias, esta função equivale a chamar getFirestore() . |
função (armazenamento de fogo...) | |
clearIndexedDbPersistence(firestore) | Limpa o armazenamento persistente. Isso inclui gravações pendentes e documentos armazenados em cache. Deve ser chamado enquanto a instância do Firestore não for iniciada (depois que o aplicativo for encerrado ou quando o aplicativo for inicializado pela primeira vez). Na inicialização, esta função deve ser chamada antes de outras funções (exceto inicializeFirestore() ou getFirestore() )). Se a instância do Firestore ainda estiver em execução, a promessa será rejeitada com o código de erro failed-precondition . Observação: clearIndexedDbPersistence() tem como objetivo principal ajudar a escrever testes confiáveis que usam o Cloud Firestore. Ele usa um mecanismo eficiente para descartar dados existentes, mas não tenta sobrescrever com segurança ou tornar irrecuperáveis os dados armazenados em cache. Para aplicativos sensíveis à divulgação de dados armazenados em cache entre sessões de usuário, recomendamos fortemente não ativar a persistência. |
coleção(firestore, caminho, pathSegments) | Obtém uma instância CollectionReference que se refere à coleção no caminho absoluto especificado. |
grupo de coleção(firestore,coleçãoId) | Cria e retorna uma nova instância Query que inclui todos os documentos no banco de dados que estão contidos em uma coleção ou subcoleção com o determinado collectionId . |
connectFirestoreEmulator(firestore, host, porta, opções) | Modifique esta instância para se comunicar com o emulador do Cloud Firestore. Nota: Isso deve ser chamado antes que esta instância seja usada para realizar qualquer operação. |
desativarRede(firestore) | Desativa o uso da rede para esta instância. Pode ser reativado via enableNetwork() . Enquanto a rede estiver desativada, quaisquer ouvintes de snapshot, chamadas getDoc() ou getDocs() retornarão resultados do cache e quaisquer operações de gravação serão enfileiradas até que a rede seja restaurada. |
doc(firestore, caminho, pathSegments) | Obtém uma instância DocumentReference que se refere ao documento no caminho absoluto especificado. |
enableIndexedDbPersistence(firestore, persistenceSettings) | Tenta ativar o armazenamento persistente, se possível. Deve ser chamado antes de qualquer outra função (exceto inicializeFirestore() , getFirestore() ou clearIndexedDbPersistence() . Se isso falhar, enableIndexedDbPersistence() rejeitará a promessa retornada. Observe que mesmo após essa falha, a instância do Firestore permanecerá utilizável, porém a persistência offline será desativada. Existem vários motivos pelos quais isso pode falhar, que podem ser identificados pelo code do erro. * pré-condição com falha: o aplicativo já está aberto em outra guia do navegador. * não implementado: O navegador é incompatível com a implementação de persistência offline. A persistência não pode ser usada em um ambiente Node.js. |
enableMultiTabIndexedDbPersistence(firestore) | Tenta ativar o armazenamento persistente com várias guias, se possível. Se habilitado em todas as guias, todas as operações compartilham acesso à persistência local, incluindo execução compartilhada de consultas e atualizações de documentos locais compensadas por latência em todas as instâncias conectadas. Se isso falhar, enableMultiTabIndexedDbPersistence() rejeitará a promessa retornada. Observe que mesmo após essa falha, a instância do Firestore permanecerá utilizável, porém a persistência offline será desativada. Existem vários motivos pelos quais isso pode falhar, que podem ser identificados pelo code do erro. * pré-condição com falha: o aplicativo já está aberto em outra guia do navegador e a multiguia não está habilitada. * não implementado: O navegador é incompatível com a implementação de persistência offline. |
ativarRede(firestore) | Reativa o uso da rede para esta instância do Firestore após uma chamada anterior para disableNetwork() . |
getPersistentCacheIndexManager(firestore) | Retorna o PersistentCache Index Manager usado pelo objeto Firestore fornecido. A instância PersistentCacheIndexManager ou null se o armazenamento persistente local não estiver em uso. |
loadBundle(firestore, bundleData) | Carrega um pacote do Firestore no cache local. |
nomeadoQuery(firestore, nome) | Lê uma consulta do Firestore do cache local, identificada pelo nome fornecido. As consultas nomeadas são empacotadas em pacotes no lado do servidor (junto com os documentos resultantes) e carregadas no cache local usando loadBundle . Uma vez no cache local, use este método para extrair uma consulta por nome. |
onSnapshotsInSync(firestore, observador) | Anexa um ouvinte para um evento de snapshots sincronizados. O evento snapshots-in-sync indica que todos os ouvintes afetados por uma determinada alteração foram acionados, mesmo que uma única alteração gerada pelo servidor afete vários ouvintes. NOTA: O evento snapshots-in-sync indica apenas que os ouvintes estão sincronizados entre si, mas não se relaciona se esses snapshots estão sincronizados com o servidor. Use SnapshotMetadata nos ouvintes individuais para determinar se um instantâneo é do cache ou do servidor. |
onSnapshotsInSync(firestore,onSync) | Anexa um ouvinte para um evento de snapshots sincronizados. O evento snapshots-in-sync indica que todos os ouvintes afetados por uma determinada alteração foram acionados, mesmo que uma única alteração gerada pelo servidor afete vários ouvintes. NOTA: O evento snapshots-in-sync indica apenas que os ouvintes estão sincronizados entre si, mas não se relaciona se esses snapshots estão sincronizados com o servidor. Use SnapshotMetadata nos ouvintes individuais para determinar se um instantâneo é do cache ou do servidor. |
runTransaction(firestore, updateFunction, opções) | Executa o updateFunction fornecido e, em seguida, tenta confirmar as alterações aplicadas na transação. Se algum documento lido na transação tiver sido alterado, o Cloud Firestore tentará novamente updateFunction . Se não conseguir confirmar após 5 tentativas, a transação falhará. O número máximo de gravações permitidas em uma única transação é 500. |
setIndexConfiguration(firestore, configuração) | (BETA) Configura a indexação para execução de consulta local. Qualquer configuração de índice anterior será substituída. A Promise é resolvida assim que a configuração do índice for persistida. As próprias entradas do índice são criadas de forma assíncrona. Você pode continuar a usar consultas que exigem indexação mesmo que os índices ainda não estejam disponíveis. A execução da consulta começará automaticamente usando o índice assim que as entradas do índice forem gravadas. Os índices são suportados apenas com persistência IndexedDb. Se IndexedDb não estiver habilitado, qualquer configuração de índice será ignorada. |
setIndexConfiguration(firestore, json) | (BETA) Configura a indexação para execução de consulta local. Qualquer configuração de índice anterior será substituída. A Promise é resolvida assim que a configuração do índice for persistida. As próprias entradas do índice são criadas de forma assíncrona. Você pode continuar a usar consultas que exigem indexação mesmo que os índices ainda não estejam disponíveis. A execução da consulta começará automaticamente usando o índice assim que as entradas do índice forem gravadas. Os índices são suportados apenas com persistência IndexedDb. Invoque enableIndexedDbPersistence() ou enableMultiTabIndexedDbPersistence() antes de definir uma configuração de índice. Se IndexedDb não estiver habilitado, qualquer configuração de índice será ignorada. O método aceita o formato JSON exportado pela Firebase CLI ( firebase firestore:indexes ). Se o formato JSON for inválido, este método gerará um erro. |
terminar (firestore) | Encerra a instância fornecida do Firestore . Depois de chamar terminate() apenas a função clearIndexedDbPersistence() pode ser usada. Qualquer outra função lançará um FirestoreError . Para reiniciar após o encerramento, crie uma nova instância do FirebaseFirestore com getFirestore() . A rescisão não cancela nenhuma gravação pendente e quaisquer promessas que aguardam uma resposta do servidor não serão resolvidas. Se você tiver a persistência habilitada, na próxima vez que iniciar esta instância, ela continuará enviando essas gravações para o servidor. Nota: Em circunstâncias normais, chamar terminate() não é necessário. Esta função é útil apenas quando você deseja forçar esta instância a liberar todos os seus recursos ou em combinação com clearIndexedDbPersistence() para garantir que todo o estado local seja destruído entre as execuções de teste. |
waitForPendingWrites(firestore) | Aguarda até que todas as gravações atualmente pendentes do usuário ativo sejam reconhecidas pelo back-end. A promessa retornada é resolvida imediatamente se não houver gravações pendentes. Caso contrário, a promessa aguardará todas as gravações emitidas anteriormente (incluindo aquelas escritas em uma sessão anterior do aplicativo), mas não aguardará as gravações que foram adicionadas após a chamada da função. Se quiser esperar por gravações adicionais, chame waitForPendingWrites() novamente. Quaisquer promessas waitForPendingWrites() pendentes são rejeitadas durante as alterações do usuário. |
writeBatch(firestore) | Cria um lote de gravação, usado para realizar várias gravações como uma única operação atômica. O número máximo de gravações permitidas em um único WriteBatch é 500. Ao contrário das transações, os lotes de gravação são persistentes offline e, portanto, são preferíveis quando você não precisa condicionar suas gravações aos dados lidos. |
função() | |
contar() | Crie um objeto AggregateField que possa ser usado para calcular a contagem de documentos no conjunto de resultados de uma consulta. |
deleteField() | Retorna uma sentinela para uso com updateDoc() ou setDoc() com {merge: true} para marcar um campo para exclusão. |
documentoId() | Retorna um FieldPath sentinela especial para se referir ao ID de um documento. Pode ser usado em consultas para classificar ou filtrar pelo ID do documento. |
getFirestore() | Retorna a instância padrão existente do Firestore associada ao FirebaseApp padrão . Se não existir nenhuma instância, inicializa uma nova instância com configurações padrão. |
memóriaEagerGarbageCollector() | Cria uma instância de MemoryEagerGarbageCollector . Este também é o coletor de lixo padrão, a menos que seja explicitamente especificado de outra forma. |
persistenteMultipleTabManager() | Cria uma instância de PersistentMultipleTabManager . |
servidorTimestamp() | Retorna um sentinela usado com setDoc() ou updateDoc() para incluir um carimbo de data/hora gerado pelo servidor nos dados gravados. |
função(databaseId...) | |
getFirestore(databaseId) | (BETA) Retorna a instância nomeada existente do Firestore associada ao FirebaseApp padrão . Se não existir nenhuma instância, inicializa uma nova instância com configurações padrão. |
função(elementos...) | |
arrayRemover(elementos) | Retorna um valor especial que pode ser usado com setDoc() ou que informa ao servidor para remover os elementos fornecidos de qualquer valor de array que já exista no servidor. Todas as instâncias de cada elemento especificado serão removidas do array. Se o campo que está sendo modificado ainda não for um array, ele será substituído por um array vazio. |
arrayUnion(elementos) | Retorna um valor especial que pode ser usado com setDoc() ou updateDoc() que informa ao servidor para unir os elementos fornecidos com qualquer valor de array que já exista no servidor. Cada elemento especificado que ainda não existe no array será adicionado ao final. Se o campo que está sendo modificado ainda não for um array, ele será substituído por um array contendo exatamente os elementos especificados. |
função(campo...) | |
média (campo) | Crie um objeto AggregateField que possa ser usado para calcular a média de um campo especificado em um intervalo de documentos no conjunto de resultados de uma consulta. |
soma(campo) | Crie um objeto AggregateField que possa ser usado para calcular a soma de um campo especificado em um intervalo de documentos no conjunto de resultados de uma consulta. |
função(campoCaminho...) | |
orderBy(fieldPath, direçãoStr) | Cria um QueryOrderByConstraint que classifica o resultado da consulta pelo campo especificado, opcionalmente em ordem decrescente em vez de crescente. Nota: Documentos que não contenham o campo especificado não estarão presentes no resultado da consulta. |
onde(fieldPath, opStr, valor) | Cria um QueryFieldFilterConstraint que impõe que os documentos devem conter o campo especificado e que o valor deve satisfazer a restrição de relação fornecida. |
função(campoValores...) | |
endAt(campoValores) | Cria um QueryEndAtConstraint que modifica o conjunto de resultados para terminar nos campos fornecidos em relação à ordem da consulta. A ordem dos valores dos campos deve corresponder à ordem das cláusulas order by da consulta. |
endBefore(campoValores) | Cria um QueryEndAtConstraint que modifica o conjunto de resultados para terminar antes dos campos fornecidos em relação à ordem da consulta. A ordem dos valores dos campos deve corresponder à ordem das cláusulas order by da consulta. |
startAfter(campoValores) | Cria um QueryStartAtConstraint que modifica o conjunto de resultados para iniciar após os campos fornecidos em relação à ordem da consulta. A ordem dos valores dos campos deve corresponder à ordem das cláusulas order by da consulta. |
startAt(campoValores) | Cria um QueryStartAtConstraint que modifica o conjunto de resultados para iniciar nos campos fornecidos em relação à ordem da consulta. A ordem dos valores dos campos deve corresponder à ordem das cláusulas order by da consulta. |
função(indexManager...) | |
deleteAllPersistentCacheIndexes(indexManager) | Remove todos os índices de cache persistentes. Observe que esta função também excluirá índices gerados por setIndexConfiguration() , que está obsoleto. |
desativarPersistentCacheIndexAutoCreation(indexManager) | Interrompe a criação automática de índices de cache persistentes para execução de consultas locais. Os índices que foram criados chamando enablePersistentCacheIndexAutoCreation() ainda terão efeito. |
enablePersistentCacheIndexAutoCreation(indexManager) | Permite que o SDK crie índices de cache persistentes automaticamente para execução de consultas locais quando o SDK acredita que os índices de cache podem ajudar a melhorar o desempenho. Este recurso está desabilitado por padrão. |
função (esquerda...) | |
agregadoFieldEqual(esquerda, direita) | Compara dois 'AggregateField ` instâncias para a igualdade. |
agregadoQuerySnapshotEqual(esquerda, direita) | Compara duas instâncias AggregateQuerySnapshot quanto à igualdade. Duas instâncias AggregateQuerySnapshot serão consideradas "iguais" se tiverem consultas subjacentes que comparem dados iguais e iguais. |
queryEqual(esquerda, direita) | Retornará verdadeiro se as consultas fornecidas apontarem para a mesma coleção e aplicarem as mesmas restrições. |
refEqual(esquerda, direita) | Retorna verdadeiro se as referências fornecidas forem iguais. |
snapshotEqual(esquerda, direita) | Retornará verdadeiro se os instantâneos fornecidos forem iguais. |
função(limite...) | |
limite(limite) | Cria um QueryLimitConstraint que retorna apenas os primeiros documentos correspondentes. |
limitToLast(limite) | Cria um QueryLimitConstraint que retorna apenas os últimos documentos correspondentes. Você deve especificar pelo menos uma cláusula orderBy para consultas limitToLast , caso contrário, uma exceção será lançada durante a execução. |
função(logLevel...) | |
setLogLevel(logLevel) | Define o detalhamento dos logs do Cloud Firestore (depuração, erro ou silencioso). |
função(n...) | |
incremento(n) | Retorna um valor especial que pode ser usado com setDoc() ou updateDoc() que informa ao servidor para incrementar o valor atual do campo pelo valor fornecido. Se o operando ou o valor do campo atual usar precisão de ponto flutuante, toda a aritmética seguirá a semântica IEEE 754. Se ambos os valores forem inteiros, os valores fora do intervalo de números seguros do JavaScript ( Number.MIN_SAFE_INTEGER a Number.MAX_SAFE_INTEGER ) também estarão sujeitos à perda de precisão. Além disso, uma vez processadas pelo back-end do Firestore, todas as operações inteiras são limitadas entre -2^63 e 2^63-1. Se o valor do campo atual não for do tipo number ou se o campo ainda não existir, a transformação definirá o campo com o valor fornecido. |
função(consulta...) | |
getAggregateFromServer(consulta, agregaçãoSpec) | Calcula as agregações especificadas sobre os documentos no conjunto de resultados da consulta determinada, sem realmente fazer download dos documentos. Usar esta função para realizar agregações é eficiente porque apenas os valores finais da agregação, e não os dados dos documentos, são baixados. Esta função pode até realizar agregações de documentos se o conjunto de resultados for proibitivamente grande para download completo (por exemplo, milhares de documentos). O resultado recebido do servidor é apresentado inalterado, sem considerar nenhum estado local. Ou seja, não são considerados os documentos do cache local, nem as modificações locais ainda não sincronizadas com o servidor. Os resultados baixados anteriormente, se houver, não são usados: toda solicitação que usa essa fonte envolve necessariamente uma viagem de ida e volta ao servidor. |
getCountFromServer(consulta) | Calcula o número de documentos no conjunto de resultados de uma determinada consulta, sem realmente fazer download dos documentos. Usar esta função para contar os documentos é eficiente porque apenas a contagem final, e não os dados dos documentos, é baixada. Esta função pode até contar os documentos se o conjunto de resultados for proibitivamente grande para download completo (por exemplo, milhares de documentos). O resultado recebido do servidor é apresentado inalterado, sem considerar nenhum estado local. Ou seja, não são considerados os documentos do cache local, nem as modificações locais ainda não sincronizadas com o servidor. Os resultados baixados anteriormente, se houver, não são usados: toda solicitação que usa essa fonte envolve necessariamente uma viagem de ida e volta ao servidor. |
getDocs(consulta) | Executa a consulta e retorna os resultados como QuerySnapshot . Nota: getDocs() tenta fornecer dados atualizados quando possível aguardando dados do servidor, mas pode retornar dados armazenados em cache ou falhar se você estiver offline e o servidor não puder ser acessado. Para especificar esse comportamento, invoque getDocsFromCache() ou getDocsFromServer() . |
getDocsFromCache(consulta) | Executa a consulta e retorna os resultados como QuerySnapshot do cache. Retorna um conjunto de resultados vazio se nenhum documento correspondente à consulta estiver armazenado em cache no momento. |
getDocsFromServer(consulta) | Executa a consulta e retorna os resultados como QuerySnapshot do servidor. Retorna um erro se a rede não estiver disponível. |
onSnapshot(consulta, observador) | Anexa um ouvinte para eventos QuerySnapshot . Você pode passar retornos de chamada onNext e onError individuais ou passar um único objeto observador com retornos de chamada next e error . O ouvinte pode ser cancelado chamando a função retornada quando onSnapshot é chamado. NOTA: Embora um retorno de chamada onCompletion possa ser fornecido, ele nunca será chamado porque o fluxo de instantâneo não tem fim. |
onSnapshot(consulta, opções, observador) | Anexa um ouvinte para eventos QuerySnapshot . Você pode passar retornos de chamada onNext e onError individuais ou passar um único objeto observador com retornos de chamada next e error . O ouvinte pode ser cancelado chamando a função retornada quando onSnapshot é chamado. NOTA: Embora um retorno de chamada onCompletion possa ser fornecido, ele nunca será chamado porque o fluxo de instantâneo não tem fim. |
onSnapshot(query, onNext, onError, onCompletion) | Anexa um ouvinte para eventos QuerySnapshot . Você pode passar retornos de chamada onNext e onError individuais ou passar um único objeto observador com retornos de chamada next e error . O ouvinte pode ser cancelado chamando a função retornada quando onSnapshot é chamado. NOTA: Embora um retorno de chamada onCompletion possa ser fornecido, ele nunca será chamado porque o fluxo de instantâneo não tem fim. |
onSnapshot(consulta, opções, onNext, onError, onCompletion) | Anexa um ouvinte para eventos QuerySnapshot . Você pode passar retornos de chamada onNext e onError individuais ou passar um único objeto observador com retornos de chamada next e error . O ouvinte pode ser cancelado chamando a função retornada quando onSnapshot é chamado. NOTA: Embora um retorno de chamada onCompletion possa ser fornecido, ele nunca será chamado porque o fluxo de instantâneo não tem fim. |
consulta(consulta, filtro composto, queryConstraints) | Cria uma nova instância imutável de Query que é estendida para incluir também restrições de consulta adicionais. |
consulta(consulta, queryConstraints) | Cria uma nova instância imutável de Query que é estendida para incluir também restrições de consulta adicionais. |
função(queryConstraints...) | |
e (queryConstraints) | Cria um novo QueryCompositeFilterConstraint que é uma conjunção das restrições de filtro fornecidas. Um filtro de conjunção inclui um documento se ele satisfizer todos os filtros fornecidos. |
ou (queryConstraints) | Cria um novo QueryCompositeFilterConstraint que é uma disjunção das restrições de filtro fornecidas. Um filtro de disjunção inclui um documento se ele satisfizer algum dos filtros fornecidos. |
função(referência...) | |
addDoc(referência, dados) | Adicione um novo documento ao CollectionReference especificado com os dados fornecidos, atribuindo-lhe um ID de documento automaticamente. |
coleção(referência, caminho, pathSegments) | Obtém uma instância CollectionReference que se refere a uma subcoleção de reference no caminho relativo especificado. |
coleção(referência, caminho, pathSegments) | Obtém uma instância CollectionReference que se refere a uma subcoleção de reference no caminho relativo especificado. |
deleteDoc(referência) | Exclui o documento referido pelo DocumentReference especificado. |
doc(referência, caminho, pathSegments) | Obtém uma instância DocumentReference que se refere a um documento dentro reference no caminho relativo especificado. Se nenhum caminho for especificado, um ID exclusivo gerado automaticamente será usado para o DocumentReference retornado. |
doc(referência, caminho, pathSegments) | Obtém uma instância DocumentReference que se refere a um documento dentro da reference no caminho relativo especificado. |
getDoc(referência) | Lê o documento referido por este DocumentReference . Nota: getDoc() tenta fornecer dados atualizados quando possível, aguardando dados do servidor, mas pode retornar dados armazenados em cache ou falhar se você estiver offline e o servidor não puder ser alcançado. Para especificar esse comportamento, invoque getDocFromCache() ou getDocFromServer() . |
getDocFromCache(referência) | Lê o documento referido por este DocumentReference do cache. Retorna um erro se o documento não estiver armazenado em cache no momento. |
getDocFromServer(referência) | Lê o documento referido por este DocumentReference do servidor. Retorna um erro se a rede não estiver disponível. |
onSnapshot(referência, observador) | Anexa um ouvinte para eventos DocumentSnapshot . Você pode passar retornos de chamada onNext e onError individuais ou passar um único objeto observador com retornos de chamada next e error . NOTA: Embora um retorno de chamada onCompletion possa ser fornecido, ele nunca será chamado porque o fluxo de instantâneo não tem fim. |
onSnapshot(referência, opções, observador) | Anexa um ouvinte para eventos DocumentSnapshot . Você pode passar retornos de chamada onNext e onError individuais ou passar um único objeto observador com retornos de chamada next e error . NOTA: Embora um retorno de chamada onCompletion possa ser fornecido, ele nunca será chamado porque o fluxo de instantâneo não tem fim. |
onSnapshot(referência, onNext, onError, onCompletion) | Anexa um ouvinte para eventos DocumentSnapshot . Você pode passar retornos de chamada onNext e onError individuais ou passar um único objeto observador com retornos de chamada next e error . NOTA: Embora um retorno de chamada onCompletion possa ser fornecido, ele nunca será chamado porque o fluxo de instantâneo não tem fim. |
onSnapshot(referência, opções, onNext, onError, onCompletion) | Anexa um ouvinte para eventos DocumentSnapshot . Você pode passar retornos de chamada onNext e onError individuais ou passar um único objeto observador com retornos de chamada next e error . NOTA: Embora um retorno de chamada onCompletion possa ser fornecido, ele nunca será chamado porque o fluxo de instantâneo não tem fim. |
setDoc(referência,dados) | Grava no documento referido por este DocumentReference . Caso o documento ainda não exista, ele será criado. |
setDoc(referência, dados, opções) | Grava no documento referido pelo DocumentReference especificado. Caso o documento ainda não exista, ele será criado. Se você fornecer merge ou mergeFields , os dados fornecidos poderão ser mesclados em um documento existente. |
updateDoc(referência, dados) | Atualiza os campos no documento referido pelo DocumentReference especificado. A atualização falhará se for aplicada a um documento que não existe. |
updateDoc(referência, campo, valor, moreFieldsAndValues) | Atualiza campos no documento referenciado pelo DocumentReference especificado. A atualização falhará se aplicada a um documento que não existe. Os campos aninhados podem ser atualizados fornecendo cadeias de caracteres de caminho de campo separadas por pontos ou fornecendo objetos FieldPath . |
função (configurações...) | |
memóriaLocalCache(configurações) | Cria uma instância de MemoryLocalCache . A instância pode ser definida como FirestoreSettings.cache para informar ao SDK qual camada de cache usar. |
memóriaLruGarbageCollector(configurações) | Cria uma instância de MemoryLruGarbageCollector . Um tamanho de destino pode ser especificado como parte do parâmetro de configuração. O coletor começará a excluir documentos quando o tamanho do cache exceder o tamanho determinado. O tamanho do cache padrão é 40 MB (40 * 1024 * 1024 bytes). |
persistenteLocalCache(configurações) | Cria uma instância de PersistentLocalCache . A instância pode ser definida como FirestoreSettings.cache para informar ao SDK qual camada de cache usar. O cache persistente não pode ser usado em um ambiente Node.js. |
persistenteSingleTabManager(configurações) | Cria uma instância de PersistentSingleTabManager . |
função (instantâneo...) | |
endAt(instantâneo) | Cria um QueryEndAtConstraint que modifica o conjunto de resultados para terminar no documento fornecido (inclusive). A posição final é relativa à ordem da consulta. O documento deve conter todos os campos fornecidos no orderBy da consulta. |
endBefore (instantâneo) | Cria um QueryEndAtConstraint que modifica o conjunto de resultados para terminar antes do documento fornecido (exclusivo). A posição final é relativa à ordem da consulta. O documento deve conter todos os campos fornecidos no orderBy da consulta. |
startAfter(instantâneo) | Cria um QueryStartAtConstraint que modifica o conjunto de resultados para iniciar após o documento fornecido (exclusivo). A posição inicial é relativa à ordem da consulta. O documento deve conter todos os campos fornecidos no orderBy da consulta. |
startAt(instantâneo) | Cria um QueryStartAtConstraint que modifica o conjunto de resultados para iniciar no documento fornecido (inclusive). A posição inicial é relativa à ordem da consulta. O documento deve conter todos os campos fornecidos no orderBy desta consulta. |
Aulas
Aula | Descrição |
---|---|
CampoAgregado | Representa uma agregação que pode ser realizada pelo Firestore. |
AggregateQuerySnapshot | Os resultados da execução de uma consulta de agregação. |
Bytes | Um objeto imutável que representa uma matriz de bytes. |
Referência de coleção | Um objeto CollectionReference pode ser usado para adicionar documentos, obter referências de documentos e consultar documentos (usando query() ). |
Referência de Documento | Um DocumentReference refere-se a um local de documento em um banco de dados Firestore e pode ser usado para gravar, ler ou ouvir o local. O documento no local referenciado pode ou não existir. |
Instantâneo do documento | Um DocumentSnapshot contém dados lidos de um documento no banco de dados do Firestore. Os dados podem ser extraídos com .data() ou .get(<field>) para obter um campo específico. Para um DocumentSnapshot que aponta para um documento inexistente, qualquer acesso a dados retornará 'indefinido'. Você pode usar o método exists() para verificar explicitamente a existência de um documento. |
CampoCaminho | Um FieldPath refere-se a um campo em um documento. O caminho pode consistir em um único nome de campo (referindo-se a um campo de nível superior no documento) ou em uma lista de nomes de campo (referindo-se a um campo aninhado no documento). Crie um FieldPath fornecendo nomes de campo. Se mais de um nome de campo for fornecido, o caminho apontará para um campo aninhado em um documento. |
CampoValor | Valores sentinela que podem ser usados ao escrever campos de documento com set() ou update() . |
Armazém de Fogo | A interface do serviço Cloud Firestore. Não chame esse construtor diretamente. Em vez disso, use getFirestore() . |
Erro Firestore | Um erro retornado por uma operação do Firestore. |
GeoPonto | Um objeto imutável que representa uma localização geográfica no Firestore. A localização é representada como par latitude/longitude. Os valores de latitude estão na faixa de [-90, 90]. Os valores de longitude estão na faixa de [-180, 180]. |
LoadBundleTask | Representa a tarefa de carregar um pacote do Firestore. Ele fornece o progresso do carregamento do pacote configurável, bem como a conclusão da tarefa e eventos de erro. A API é compatível com Promise<LoadBundleTaskProgress> . |
PersistentCacheIndexManager | Um PersistentCacheIndexManager para configurar índices de cache persistentes usados para execução de consulta local. Para usar, chame getPersistentCacheIndexManager() para obter uma instância. |
Consulta | Uma Query refere-se a uma consulta que você pode ler ou ouvir. Você também pode construir objetos Query refinados adicionando filtros e ordenando. |
QueryCompositeFilterConstraint | Um QueryCompositeFilterConstraint é usado para restringir o conjunto de documentos retornados por uma consulta do Firestore executando o OR ou AND lógico de vários QueryFieldFilterConstraint s ou QueryCompositeFilterConstraint S. QueryCompositeFilterConstraint s são criados invocando or() ou and() e podem então ser passados para query() para criar uma nova instância de consulta que também contém QueryCompositeFilterConstraint . |
QueryConstraint | Um QueryConstraint é usado para restringir o conjunto de documentos retornados por uma consulta do Firestore. QueryConstraint s são criados invocando where() , ordenarBy() , startAt() , começarDepois() , fimAntes() , fimAt() , limite() , limitToLast() e pode então ser passado para query() para criar uma nova instância de consulta que também contém este QueryConstraint . |
QueryDocumentSnapshot | Um QueryDocumentSnapshot contém dados lidos de um documento no banco de dados do Firestore como parte de uma consulta. É garantida a existência do documento e seus dados podem ser extraídos com .data() ou .get(<field>) para obter um campo específico. Um QueryDocumentSnapshot oferece a mesma superfície de API que um DocumentSnapshot . Como os resultados da consulta contêm apenas documentos existentes, a propriedade exists sempre será verdadeira e data() nunca retornará 'indefinido'. |
QueryEndAtConstraint | Um QueryEndAtConstraint é usado para excluir documentos do final de um conjunto de resultados retornado por uma consulta do Firestore. QueryEndAtConstraint s são criados invocando endAt() ou endBefore() e podem então ser passados para query() para criar uma nova instância de consulta que também contém este QueryEndAtConstraint . |
QueryFieldFilterConstraint | Um QueryFieldFilterConstraint é usado para restringir o conjunto de documentos retornados por uma consulta do Firestore, filtrando um ou mais campos do documento. QueryFieldFilterConstraint s são criados invocando where() e podem então ser passados para query() para criar uma nova instância de consulta que também contém este QueryFieldFilterConstraint . |
QueryLimitConstraint | Um QueryLimitConstraint é usado para limitar o número de documentos retornados por uma consulta do Firestore. QueryLimitConstraint s são criados invocando limit() ou limitToLast() e podem então ser passados para query() para criar uma nova instância de consulta que também contém este QueryLimitConstraint . |
QueryOrderByConstraint | Um QueryOrderByConstraint é usado para classificar o conjunto de documentos retornados por uma consulta do 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 '<', '<=', '==', '!=', '>=', '>', '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:
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:
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:
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 ofPersistentLocalCache
to turn on IndexedDb cache. Calling this function whenFirestoreSettings.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 ofPersistentLocalCache
to turn on indexeddb cache. Calling this function whenFirestoreSettings.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:
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:
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:
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:
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:
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:
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:
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:
persistentMultipleTabManager()
Creates an instance of PersistentMultipleTabManager
.
Signature:
export declare function persistentMultipleTabManager(): PersistentMultipleTabManager;
Returns:
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:
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:
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:
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:
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:
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 "<", "<=", "==", "<", "<=", "!="). |
value | unknown | The value for comparison |
Returns:
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:
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:
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:
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:
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:
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:
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:
|
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:
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:
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:
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:
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:
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:
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:
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:
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:
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:
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:
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:
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:
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:
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:
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:
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:
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 '<', '<=', '==', '!=', '>=', '>', '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);