@capacitor-firebase/firestore

中文文档
8.6.0发布于 2026/10/31Apache-2.0TypeScriptESM + CJS零依赖构建来源已验证近 30 天下载 1.8万

Capacitor plugin for Firebase Cloud Firestore on Android, iOS, and Web.

原始使用文档
文档目录55 节
  1. Use Cases
  2. Compatibility
  3. Guides
  4. Installation
  5. Android
  6. iOS
  7. Configuration
  8. Examples
  9. Demo
  10. Starter templates
  11. Usage
  12. Create a document
  13. Read a document
  14. Update or delete a document
  15. Update a document with field values
  16. Perform a batched write
  17. Query a collection
  18. Control network access
  19. Use the Firebase Emulator
  20. Listen for real-time updates
  21. Remove listeners
  22. API
  23. addDocument(...)
  24. addCollectionGroupSnapshotListener(...)
  25. addCollectionSnapshotListener(...)
  26. addDocumentSnapshotListener(...)
  27. clearPersistence()
  28. deleteDocument(...)
  29. disableNetwork()
  30. disablePersistence()
  31. enablePersistence(...)
  32. enableNetwork()
  33. getCollection(...)
  34. getCollectionGroup(...)
  35. getCountFromServer(...)
  36. getDocument(...)
  37. removeAllListeners()
  38. removeSnapshotListener(...)
  39. setDocument(...)
  40. updateDocument(...)
  41. useEmulator(...)
  42. writeBatch(...)
  43. Interfaces
  44. Type Aliases
  45. FAQ
  46. How do I get notified about data changes in real time?
  47. What is the difference between getCollection and getCollect…
  48. Does the plugin work offline?
  49. Can I use a Firestore database other than the default one?
  50. How do I test my app against a local Firestore instance?
  51. Can I use this plugin with Ionic, React, Vue or Angular?
  52. Related Plugins
  53. Newsletter
  54. Changelog
  55. License

Capacitor Firebase Cloud Firestore Plugin

Unofficial Capacitor plugin for Firebase Cloud Firestore.[^1]

Use Cases

The Cloud Firestore plugin is typically used to store and sync app data in the cloud, for example:

  • Real-time updates: Keep your UI up to date by listening to document and collection changes with snapshot listeners.
  • User-generated content: Create, read, update, and delete documents for user profiles, posts, or other app data.
  • Complex queries: Filter and sort collections with composite filters and query constraints such as where, orderBy, and limit.
  • Offline support: Enable offline persistence and control network access to work with locally cached data.
  • Atomic writes: Perform multiple write operations as a single atomic batch with writeBatch(...).

Compatibility

Plugin VersionCapacitor VersionStatus
8.x.x>=8.x.xActive support
7.x.x7.x.xDeprecated
6.x.x6.x.xDeprecated

Guides

Installation

You can use our AI-Assisted Setup to install the plugin. Add the Capawesome Skills to your AI tool using the following command:

npx skills add capawesome-team/skills --skill capacitor-plugins

Then use the following prompt:

Use the `capacitor-plugins` skill from `capawesome-team/skills` to install the `@capacitor-firebase/firestore` plugin in my project.

If you prefer Manual Setup, install the plugin by running the following commands and follow the platform-specific instructions below:

npm install @capacitor-firebase/firestore
npx cap sync

Add Firebase to your project if you haven't already (Android / iOS / Web).

Android

Variables

If needed, you can define the following project variable in your app’s variables.gradle file to change the default version of the dependency:

  • $firebaseFirestoreVersion version of com.google.firebase:firebase-firestore (default: 26.0.2)

This can be useful if you encounter dependency conflicts with other plugins in your project.

iOS

Swift Package Manager

Add the following to your capacitor.config.json (or capacitor.config.ts) to avoid a SwiftPM package identity collision:

{
  "experimental": {
    "ios": {
      "spm": {
        "packageOptions": {
          "@capacitor-firebase/firestore": {
            "symlink": true
          }
        }
      }
    }
  }
}

Attention: SPM packageOptions support requires Capacitor CLI 8.4.0+.

Configuration

These configuration values are available:

PropTypeDescriptionSince
databaseIdstringThe database ID of the Firestore database to use. Only available for Android and iOS.8.2.0

Examples

In capacitor.config.json:

{
  "plugins": {
    "FirebaseFirestore": {
      "databaseId": undefined
    }
  }
}

In capacitor.config.ts:

/// <reference types="@capacitor-firebase/firestore" />

import { CapacitorConfig } from '@capacitor/cli';

const config: CapacitorConfig = {
  plugins: {
    FirebaseFirestore: {
      databaseId: undefined,
    },
  },
};

export default config;

Demo

A working example can be found here: robingenz/capacitor-firebase-plugin-demo

Starter templates

The following starter templates are available:

Usage

The following examples show how to create, read, update, and delete documents, update documents with field values, perform batched writes, query collections, control network access, use the Firebase Emulator, and listen for and remove real-time updates.

Create a document

Add a new document to a collection with an auto-generated ID, or write a document at a known reference with setDocument(...). Set merge to true to merge the data with an existing document:

import { FirebaseFirestore } from '@capacitor-firebase/firestore';

const addDocument = async () => {
  await FirebaseFirestore.addDocument({
    reference: 'users',
    data: { 
      first: 'Alan', 
      last: 'Turing', 
      born: 1912 
    },
  });
};

const setDocument = async () => {
  await FirebaseFirestore.setDocument({
    reference: 'users/Aorq09lkt1ynbR7xhTUx',
    data: { 
      first: 'Alan', 
      last: 'Turing', 
      born: 1912 
    },
    merge: true,
  });
};

Read a document

Read a single document by its reference:

import { FirebaseFirestore } from '@capacitor-firebase/firestore';

const getDocument = async () => {
  const { snapshot } = await FirebaseFirestore.getDocument({
    reference: 'users/Aorq09lkt1ynbR7xhTUx',
  });
  return snapshot;
};

Update or delete a document

Update fields of an existing document or delete it entirely:

import { FirebaseFirestore } from '@capacitor-firebase/firestore';

const updateDocument = async () => {
  await FirebaseFirestore.updateDocument({
    reference: 'users/Aorq09lkt1ynbR7xhTUx',
    data: { 
      first: 'Alan', 
      last: 'Turing', 
      born: 1912 
    },
  });
};

const deleteDocument = async () => {
  await FirebaseFirestore.deleteDocument({
    reference: 'users/Aorq09lkt1ynbR7xhTUx',
  });
};

Update a document with field values

Use FieldValue helpers to increment numbers, set server timestamps, modify arrays, or delete fields:

import { FieldValue, FirebaseFirestore } from '@capacitor-firebase/firestore';

const updateDocumentWithFieldValue = async () => {
  await FirebaseFirestore.updateDocument({
    reference: 'users/Aorq09lkt1ynbR7xhTUx',
    data: {
      born: FieldValue.increment(1),
      updatedAt: FieldValue.serverTimestamp(),
      nicknames: FieldValue.arrayUnion('Prof'),
      tags: FieldValue.arrayRemove('draft'),
      deprecatedField: FieldValue.delete(),
    },
  });
};

Perform a batched write

Execute multiple set, update, and delete operations as a single atomic batch:

import { FirebaseFirestore } from '@capacitor-firebase/firestore';

const writeBatch = async () => {
  await FirebaseFirestore.writeBatch({
    operations: [
      {
        type: 'set',
        reference: 'users/Aorq09lkt1ynbR7xhTUx',
        data: { 
          first: 'Alan', 
          last: 'Turing', 
          born: 1912 
        },
        options: { merge: true },
      },
      {
        type: 'update',
        reference: 'users/Aorq09lkt1ynbR7xhTUx',
        data: { 
          first: 'Alan', 
          last: 'Turing', 
          born: 1912 
        },
      },
      {
        type: 'delete',
        reference: 'users/Aorq09lkt1ynbR7xhTUx',
      },
    ],
  });
};

Query a collection

Read multiple documents from a collection or a collection group. You can filter the results with a composite filter and apply query constraints such as orderBy and limit:

import { FirebaseFirestore } from '@capacitor-firebase/firestore';

const getCollection = async () => {
  const { snapshots } = await FirebaseFirestore.getCollection({
    reference: 'users',
    compositeFilter: {
      type: 'and',
      queryConstraints: [
        {
          type: 'where',
          fieldPath: 'born',
          opStr: '==',
          value: 1912,
        },
      ],
    },
    queryConstraints: [
      {
        type: 'orderBy',
        fieldPath: 'born',
        directionStr: 'desc',
      },
      {
        type: 'limit',
        limit: 10,
      },
    ],
  });
  return snapshots;
};

const getCollectionGroup = async () => {
  const { snapshots } = await FirebaseFirestore.getCollectionGroup({
    reference: 'users',
    compositeFilter: {
      type: 'and',
      queryConstraints: [
        {
          type: 'where',
          fieldPath: 'born',
          opStr: '==',
          value: 1912,
        },
      ],
    },
    queryConstraints: [
      {
        type: 'orderBy',
        fieldPath: 'born',
        directionStr: 'desc',
      },
      {
        type: 'limit',
        limit: 10,
      },
    ],
  });
  return snapshots;
};

Control network access

Disable and re-enable the use of the network, for example to force the plugin to work with locally cached data:

import { FirebaseFirestore } from '@capacitor-firebase/firestore';

const enableNetwork = async () => {
  await FirebaseFirestore.enableNetwork();
};

const disableNetwork = async () => {
  await FirebaseFirestore.disableNetwork();
};

Use the Firebase Emulator

Connect the plugin to a local Firebase Emulator instance during development:

import { FirebaseFirestore } from '@capacitor-firebase/firestore';

const useEmulator = async () => {
  await FirebaseFirestore.useEmulator({
    host: '10.0.2.2',
    port: 9001,
  });
};

Listen for real-time updates

Attach snapshot listeners to a document, a collection, or a collection group to get notified whenever the data changes:

import { FirebaseFirestore } from '@capacitor-firebase/firestore';

const addDocumentSnapshotListener = async () => {
  const callbackId = await FirebaseFirestore.addDocumentSnapshotListener(
    {
      reference: 'users/Aorq09lkt1ynbR7xhTUx',
    },
    (event, error) => {
      if (error) {
        console.error(error);
      } else {
        console.log(event);
      }
    }
  );
  return callbackId;
};

const addCollectionSnapshotListener = async () => {
  const callbackId = await FirebaseFirestore.addCollectionSnapshotListener(
    {
      reference: 'users',
      compositeFilter: {
        type: 'and',
        queryConstraints: [
          {
            type: 'where',
            fieldPath: 'born',
            opStr: '==',
            value: 1912,
          },
        ],
      },
      queryConstraints: [
        {
          type: 'orderBy',
          fieldPath: 'born',
          directionStr: 'desc',
        },
        {
          type: 'limit',
          limit: 10,
        },
      ],
    },
    (event, error) => {
      if (error) {
        console.error(error);
      } else {
        console.log(event);
      }
    }
  );
  return callbackId;
};

const addCollectionGroupSnapshotListener = async () => {
  const callbackId = await FirebaseFirestore.addCollectionGroupSnapshotListener(
    {
      reference: 'users',
      compositeFilter: {
        type: 'and',
        queryConstraints: [
          {
            type: 'where',
            fieldPath: 'born',
            opStr: '==',
            value: 1912,
          },
        ],
      },
      queryConstraints: [
        {
          type: 'orderBy',
          fieldPath: 'born',
          directionStr: 'desc',
        },
        {
          type: 'limit',
          limit: 10,
        },
      ],
    },
    (event, error) => {
      if (error) {
        console.error(error);
      } else {
        console.log(event);
      }
    }
  );
  return callbackId;
};

Remove listeners

Remove a single snapshot listener by its callback ID or remove all listeners at once:

import { FirebaseFirestore } from '@capacitor-firebase/firestore';

const removeSnapshotListener = async (callbackId: string) => {
  await FirebaseFirestore.removeSnapshotListener({
    callbackId,
  });
};

const removeAllListeners = async () => {
  await FirebaseFirestore.removeAllListeners();
};

API

addDocument(...)

addDocument(options: AddDocumentOptions) => Promise<AddDocumentResult>

Adds a new document to a collection with the given data.

ParamType
optionsAddDocumentOptions

Returns: Promise<AddDocumentResult>

Since: 5.2.0


addCollectionGroupSnapshotListener(...)

addCollectionGroupSnapshotListener<T extends DocumentData = DocumentData>(options: AddCollectionGroupSnapshotListenerOptions, callback: AddCollectionGroupSnapshotListenerCallback<T>) => Promise<CallbackId>

Adds a listener for collection group snapshot events.

ParamType
optionsAddCollectionGroupSnapshotListenerOptions
callbackAddCollectionGroupSnapshotListenerCallback<T>

Returns: Promise<string>

Since: 6.1.0


addCollectionSnapshotListener(...)

addCollectionSnapshotListener<T extends DocumentData = DocumentData>(options: AddCollectionSnapshotListenerOptions, callback: AddCollectionSnapshotListenerCallback<T>) => Promise<CallbackId>

Adds a listener for collection snapshot events.

ParamType
optionsAddCollectionSnapshotListenerOptions
callbackAddCollectionSnapshotListenerCallback<T>

Returns: Promise<string>

Since: 5.2.0


addDocumentSnapshotListener(...)

addDocumentSnapshotListener<T extends DocumentData = DocumentData>(options: AddDocumentSnapshotListenerOptions, callback: AddDocumentSnapshotListenerCallback<T>) => Promise<CallbackId>

Adds a listener for document snapshot events.

ParamType
optionsAddDocumentSnapshotListenerOptions
callbackAddDocumentSnapshotListenerCallback<T>

Returns: Promise<string>

Since: 5.2.0


clearPersistence()

clearPersistence() => Promise<void>

Clears the persistent storage. This includes pending writes and cached documents.

Attention: Must be called after the app is shutdown or when the app is first initialized.

Since: 5.2.0


deleteDocument(...)

deleteDocument(options: DeleteDocumentOptions) => Promise<void>

Deletes the document referred to by the specified reference.

ParamType
optionsDeleteDocumentOptions

Since: 5.2.0


disableNetwork()

disableNetwork() => Promise<void>

Disables use of the network.

Since: 5.2.0


disablePersistence()

disablePersistence() => Promise<void>

Disables offline persistence.

Attention: Must be called before any other Firestore method.

Since: 8.2.0


enablePersistence(...)

enablePersistence(options?: EnablePersistenceOptions | undefined) => Promise<void>

Enables offline persistence.

Attention: Must be called before any other Firestore method.

ParamType
optionsEnablePersistenceOptions

Since: 8.2.0


enableNetwork()

enableNetwork() => Promise<void>

Re-enables use of the network.

Since: 5.2.0


getCollection(...)

getCollection<T extends DocumentData = DocumentData>(options: GetCollectionOptions) => Promise<GetCollectionResult<T>>

Reads the collection referenced by the specified reference.

ParamType
optionsGetCollectionOptions

Returns: Promise<GetCollectionResult<T>>

Since: 5.2.0


getCollectionGroup(...)

getCollectionGroup<T extends DocumentData = DocumentData>(options: GetCollectionGroupOptions) => Promise<GetCollectionGroupResult<T>>

Reads the collection group referenced by the specified reference.

ParamType
optionsGetCollectionGroupOptions

Returns: Promise<GetCollectionGroupResult<T>>


getCountFromServer(...)

getCountFromServer(options: GetCountFromServerOptions) => Promise<GetCountFromServerResult>

Fetches the number of documents in a collection.

ParamType
optionsGetCountFromServerOptions

Returns: Promise<GetCountFromServerResult>

Since: 6.4.0


getDocument(...)

getDocument<T extends DocumentData = DocumentData>(options: GetDocumentOptions) => Promise<GetDocumentResult<T>>

Reads the document referred to by the specified reference.

ParamType
optionsGetDocumentOptions

Returns: Promise<GetDocumentResult<T>>

Since: 5.2.0


removeAllListeners()

removeAllListeners() => Promise<void>

Remove all listeners for this plugin.

Since: 5.2.0


removeSnapshotListener(...)

removeSnapshotListener(options: RemoveSnapshotListenerOptions) => Promise<void>

Remove a listener for document or collection snapshot events.

ParamType
optionsRemoveSnapshotListenerOptions

Since: 5.2.0


setDocument(...)

setDocument(options: SetDocumentOptions) => Promise<void>

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

ParamType
optionsSetDocumentOptions

Since: 5.2.0


updateDocument(...)

updateDocument(options: UpdateDocumentOptions) => Promise<void>

Updates fields in the document referred to by the specified reference.

ParamType
optionsUpdateDocumentOptions

Since: 5.2.0


useEmulator(...)

useEmulator(options: UseEmulatorOptions) => Promise<void>

Instrument your app to talk to the Firestore emulator.

ParamType
optionsUseEmulatorOptions

Since: 6.1.0


writeBatch(...)

writeBatch(options: WriteBatchOptions) => Promise<void>

Execute multiple write operations as a single batch.

ParamType
optionsWriteBatchOptions

Since: 6.1.0


Interfaces

AddDocumentResult

PropTypeDescriptionSince
referenceDocumentReferenceThe reference of the newly added document.5.2.0

AddDocumentOptions

PropTypeDescriptionSince
referencestringThe reference as a string, with path components separated by a forward slash (/).5.2.0
dataDocumentDataAn object containing the data for the new document.5.2.0

DocumentData

AddCollectionGroupSnapshotListenerOptions

PropTypeDescriptionSince
referencestringThe reference as a string, with path components separated by a forward slash (/).6.1.0
compositeFilterQueryCompositeFilterConstraintThe filter to apply.6.1.0
queryConstraintsQueryNonFilterConstraint[]Narrow or order the set of documents to retrieve, but do not explicitly filter for document fields.6.1.0

QueryCompositeFilterConstraint

PropTypeDescriptionSince
type'and' | 'or'The type of the constraint.5.2.0
queryConstraintsQueryFilterConstraint[]The filters to apply.5.2.0

QueryFieldFilterConstraint

PropTypeDescriptionSince
type'where'The type of the constraint.5.2.0
fieldPathstringThe path to compare.5.2.0
opStrQueryOperatorThe operation string to apply.5.2.0
valueanyThe value for comparison.5.2.0

QueryOrderByConstraint

PropTypeDescriptionSince
type'orderBy'The type of the constraint.5.2.0
fieldPathstringThe path to compare.5.2.0
directionStrOrderByDirectionThe direction to sort by.5.2.0

QueryLimitConstraint

PropTypeDescriptionSince
type'limit' | 'limitToLast'The type of the constraint.5.2.0
limitnumberThe maximum number of items to return.5.2.0

QueryStartAtConstraint

PropTypeDescriptionSince
type'startAt' | 'startAfter'The type of the constraint.5.2.0
referencestringThe reference to start at or after as a string, with path components separated by a forward slash (/). Attention: This requires an additional document read.5.2.0

QueryEndAtConstraint

PropTypeDescriptionSince
type'endAt' | 'endBefore'The type of the constraint.5.2.0
referencestringThe reference as to end at or before as a string, with path components separated by a forward slash (/). Attention: This requires an additional document read.5.2.0

GetCollectionGroupResult

PropTypeDescriptionSince
snapshotsDocumentSnapshot<T>[]The documents in the collection.5.2.0

DocumentSnapshot

PropTypeDescriptionSince
idstringThe document's identifier within its collection.5.2.0
pathstringThe path of the document.5.2.0
dataT | nullAn object containing the data for the document. Returns null if the document doesn't exist.5.2.0
metadataSnapshotMetadataMetadata about the snapshot, concerning its source and if it has local modifications.6.2.0

SnapshotMetadata

PropTypeDescriptionSince
fromCachebooleanTrue if the snapshot was created from cached data.6.2.0
hasPendingWritesbooleanTrue if the snapshot was created from pending write data.6.2.0

AddCollectionSnapshotListenerOptions

PropTypeDescriptionSince
referencestringThe reference as a string, with path components separated by a forward slash (/).5.2.0
compositeFilterQueryCompositeFilterConstraintThe filter to apply.5.2.0
queryConstraintsQueryNonFilterConstraint[]Narrow or order the set of documents to retrieve, but do not explicitly filter for document fields.5.2.0

GetCollectionResult

PropTypeDescriptionSince
snapshotsDocumentSnapshot<T>[]The documents in the collection.5.2.0

AddDocumentSnapshotListenerOptions

PropTypeDescriptionSince
referencestringThe reference as a string, with path components separated by a forward slash (/).5.2.0

GetDocumentResult

PropTypeDescriptionSince
snapshotDocumentSnapshot<T>The current document contents.5.2.0

DeleteDocumentOptions

PropTypeDescriptionSince
referencestringThe reference as a string, with path components separated by a forward slash (/).5.2.0

EnablePersistenceOptions

PropTypeDescriptionDefaultSince
cacheSizeBytesnumberThe cache size in bytes.104857600 (100 MB)8.2.0
synchronizeTabsbooleanWhether to synchronize persistence across multiple tabs. Only available for Web.false8.2.0

GetCollectionOptions

PropTypeDescriptionSince
referencestringThe reference as a string, with path components separated by a forward slash (/).5.2.0
compositeFilterQueryCompositeFilterConstraintThe filter to apply.5.2.0
queryConstraintsQueryNonFilterConstraint[]Narrow or order the set of documents to retrieve, but do not explicitly filter for document fields.5.2.0

GetCollectionGroupOptions

PropTypeDescriptionSince
referencestringThe reference as a string, with path components separated by a forward slash (/).5.2.0
compositeFilterQueryCompositeFilterConstraintThe filter to apply.5.2.0
queryConstraintsQueryNonFilterConstraint[]Narrow or order the set of documents to retrieve, but do not explicitly filter for document fields.5.2.0

GetCountFromServerResult

PropTypeDescriptionSince
countnumberThe number of documents in the collection.6.4.0

GetCountFromServerOptions

PropTypeDescriptionSince
referencestringThe reference as a string, with path components separated by a forward slash (/).6.4.0
compositeFilterQueryCompositeFilterConstraintThe filter to apply.8.3.0
queryConstraintsQueryNonFilterConstraint[]Narrow or order the set of documents to count, but do not explicitly filter for document fields.8.3.0

GetDocumentOptions

PropTypeDescriptionSince
referencestringThe reference as a string, with path components separated by a forward slash (/).5.2.0

RemoveSnapshotListenerOptions

PropTypeSince
callbackIdCallbackId5.2.0

SetDocumentOptions

PropTypeDescriptionDefaultSince
referencestringThe reference as a string, with path components separated by a forward slash (/).5.2.0
dataDocumentDataAn object containing the data for the new document.5.2.0
mergebooleanWhether to merge the provided data with an existing document.false5.2.0

UpdateDocumentOptions

PropTypeDescriptionSince
referencestringThe reference as a string, with path components separated by a forward slash (/).5.2.0
dataDocumentDataAn object containing the data for the new document.5.2.0

UseEmulatorOptions

PropTypeDescriptionDefaultSince
hoststringThe emulator host without any port or scheme. Note when using a Android Emulator device: 10.0.2.2 is the special IP address to connect to the 'localhost' of the host computer.6.1.0
portnumberThe emulator port.80806.1.0

WriteBatchOptions

PropTypeDescriptionSince
operationsWriteBatchOperation[]The operations to execute in the batch.6.1.0

WriteBatchOperation

PropTypeDescriptionSince
type'set' | 'update' | 'delete'The type of operation.6.1.0
referencestringThe reference as a string, with path components separated by a forward slash (/).6.1.0
dataDocumentDataAn object containing the data for the new document.6.1.0
optionsSetOptionsAn object to configure the set behavior.7.3.0

SetOptions

PropTypeDescriptionDefaultSince
mergebooleanWhether a merge should be performed or the document should be overwritten.false7.3.0

Type Aliases

QueryFilterConstraint

QueryFieldFilterConstraint | QueryCompositeFilterConstraint

QueryOperator

'<' | '<=' | '==' | '>=' | '>' | '!=' | 'array-contains' | 'array-contains-any' | 'in' | 'not-in'

QueryNonFilterConstraint

QueryOrderByConstraint | QueryLimitConstraint | QueryStartAtConstraint | QueryEndAtConstraint

OrderByDirection

'desc' | 'asc'

AddCollectionGroupSnapshotListenerCallback

(event: AddCollectionGroupSnapshotListenerCallbackEvent<T> | null, error: any): void

AddCollectionGroupSnapshotListenerCallbackEvent

GetCollectionGroupResult<T>

CallbackId

string

AddCollectionSnapshotListenerCallback

(event: AddCollectionSnapshotListenerCallbackEvent<T> | null, error: any): void

AddCollectionSnapshotListenerCallbackEvent

GetCollectionResult<T>

AddDocumentSnapshotListenerCallback

(event: AddDocumentSnapshotListenerCallbackEvent<T> | null, error: any): void

AddDocumentSnapshotListenerCallbackEvent

GetDocumentResult<T>

FAQ

How do I get notified about data changes in real time?

Attach a snapshot listener with addDocumentSnapshotListener(...), addCollectionSnapshotListener(...), or addCollectionGroupSnapshotListener(...). The callback is invoked whenever the observed data changes. Each listener returns a callback ID that you can later pass to removeSnapshotListener(...), or you can remove all listeners at once with removeAllListeners(). See Listen for real-time updates for an example.

What is the difference between getCollection and getCollectionGroup?

The getCollection(...) method reads the documents of a single collection at the given reference. The getCollectionGroup(...) method reads the documents of a collection group, which consists of all collections with the same ID. Both methods support composite filters and query constraints.

Does the plugin work offline?

Yes, you can enable offline persistence with the enablePersistence(...) method, which must be called before any other Firestore method. You can also disable and re-enable the use of the network with disableNetwork() and enableNetwork(). The persistent storage, including pending writes and cached documents, can be cleared with clearPersistence(), which must be called after the app is shut down or when it is first initialized.

Can I use a Firestore database other than the default one?

Yes, you can set the databaseId configuration option in your Capacitor configuration to select the Firestore database to use (see Configuration). This option is only available on Android and iOS.

How do I test my app against a local Firestore instance?

Use the useEmulator(...) method to connect the plugin to a local Firebase Emulator instance by providing its host and port. This allows you to develop and test without touching your production data.

Can I use this plugin with Ionic, React, Vue or Angular?

Yes, the plugin is framework-agnostic. It works in any Capacitor app regardless of the web framework, including Ionic with Angular, React, or Vue, as well as plain JavaScript projects.

Newsletter

Stay up to date with the latest news and updates about the Capawesome, Capacitor, and Ionic ecosystem by subscribing to our Capawesome Newsletter.

Changelog

See CHANGELOG.md.

License

See LICENSE.

[^1]: This project is not affiliated with, endorsed by, sponsored by, or approved by Google LLC or any of their affiliates or subsidiaries.

版本与发布记录

@capacitor-firebase/firestore 共发布 36 个版本,首次发布于 2023/09/27;过去 12 个月发布了 13 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
8.6.0latest2026/10/319 天前
8.5.22026/09/171 个月前
8.5.12026/09/022 个月前
8.5.02026/08/312 个月前
8.4.02026/08/122 个月前
8.3.02026/06/045 个月前

其他发布通道:dev → 7.0.0-dev.1765887457。

关于 @capacitor-firebase/firestore 的常见问题

@capacitor-firebase/firestore 是什么?

Capacitor plugin for Firebase Cloud Firestore on Android, iOS, and Web.

如何安装 @capacitor-firebase/firestore?

在项目目录运行 npm install @capacitor-firebase/firestore,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:@capacitor/core(>=8.0.0)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@capacitor-firebase/firestore 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@capacitor-firebase/firestore 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@capacitor-firebase/firestore 可以商用吗?

@capacitor-firebase/firestore 使用 Apache-2.0 许可。宽松许可:允许商业使用、修改和再分发,并附带明确的专利授权;分发时需保留许可与 NOTICE 文件,修改过的文件要注明改动。以上为概括,不构成法律意见,请以许可原文为准。

@capacitor-firebase/firestore 的下载量有多少?

根据 npm 官方下载统计,@capacitor-firebase/firestore 在 2026/10/09 – 2026/11/07 这 30 天内被下载 18,043 次,日均约 601 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@capacitor-firebase/firestore 还在维护吗?

最新版本 8.6.0 发布于 2026/10/31(9 天前);至今共发布 36 个版本,其中过去 12 个月发布了 13 个;首次发布于 2023/09/27。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。