---
title: Cloud Firestore
description: >-
  Cloud Firestore API guide: getFirestore/initializeFirestore settings,
  emulator, getDoc/getDocs (cache/server), onSnapshot options and error
  handling, queries (where/and/or/Filter, collectionGroup, documentId,
  FieldPath, cursors, limitToLast), writes (setDoc merge, increment, vector),
  withConverter, transactions/batches, aggregates, offline (enableNetwork,
  clearPersistence), cache indexes, bundles (LoadBundleTask), error codes, and
  RN helpers (SDK_VERSION).
next: /firestore/emulator
previous: /auth/multi-factor-auth
---
> ## Documentation Index
> Fetch the complete documentation index at: https://rnfirebase.io/llms.txt
> Use this file to discover all available pages before exploring further.

## Prerequisites

- `@react-native-firebase/app` installed and native config completed per [Getting Started](/) (Android `google-services.json`, iOS `GoogleService-Info.plist`, Expo config plugin, or React Native CLI setup). From v26, New Architecture is required for packages with a native bridge.
- Install Firestore: `npm install --save @react-native-firebase/firestore` or `yarn add @react-native-firebase/firestore`, then rebuild native apps (`cd ios && pod install` on iOS).
- Enable Cloud Firestore in the [Firebase Console](https://console.firebase.google.com/) for your project and deploy security rules appropriate for your app.

Example Expo Router screen: https://github.com/invertase/react-native-firebase/blob/main/test-expo/app/firestore.tsx

# Installation

This module requires that the `@react-native-firebase/app` module is already setup and installed. To install the "app" module, view the
[Getting Started](/) documentation.

```bash
# Install & setup the app module
yarn add @react-native-firebase/app

# Install the firestore module
yarn add @react-native-firebase/firestore

# If you're developing your app using iOS, run this command
cd ios/ && pod install
```

If you receive an `app:mergeDexDebug` error after adding Cloud Firestore, multidex is not the fix. Android supports it natively at every `minSdk` React Native Firebase v27 supports, so read the full Gradle output for the underlying cause.

# Platform support and New Architecture

{/* prettier-ignore */}
| | |
| --- | --- |
| **Platforms** | Android, iOS (native Firebase SDK); macOS via firebase-js-sdk web interop |
| **New Architecture** | **Required** from v26. See [Migrating to v26](/migrating-to-v26#new-architecture-requirement). |

**Platform notes:** On iOS and Android, the web-only `localCache` values (`memoryLocalCache`, `persistentLocalCache`, IndexedDB factories) are **not supported**, and persistence is controlled by the native Firestore SDK through `initializeFirestore` settings (for example `persistence` and `cacheSizeBytes`). On macOS, settings are passed to the firebase-js-sdk Firestore Lite `initializeFirestore`, which has no local cache or persistence. `initializeFirestore` returns `Firestore` synchronously, applies settings in the background, and reports settings errors with `console.warn` (see [Settings](#settings)). React Native Firebase also exports RN-only helpers such as `SDK_VERSION`, `clearPersistence`, and `Filter`, plus type aliases `FirebaseApp`, `FirebaseSignInProvider`, `FirebaseIdToken`, and `LiteTransaction`. Each is explained in the section that uses it.

# What does it do

Firestore is a flexible, scalable NoSQL cloud database to store and sync data. It keeps your data in sync across client
apps through realtime listeners and offers offline support so you can build responsive apps that work regardless of network
latency or Internet connectivity.

<YouTube id="QcsAb2RR52c" />

# Usage

## Emulator

Call `connectFirestoreEmulator` before any Firestore reads, writes, or listeners when talking to the Local Emulator Suite (the Firestore emulator listens on port `8080` by default). The call takes a non-empty host and a numeric port. It applies once per app and database: a second call for the same instance is ignored by the native layer, so do not use it to switch hosts at runtime. See also [Cloud Firestore Emulator](/firestore/emulator).

On Android, `localhost` and `127.0.0.1` are rewritten to `10.0.2.2` (the host machine as seen from the Android emulator) and a message is logged. The rewrite is controlled by the `android_bypass_emulator_url_remap` key in `firebase.json` (see [JSON Config](/app/json-config)). Pass the real IP address when running on a physical device.

`FirebaseApp` is the React Native Firebase app type re-exported for `getFirestore(app)` and `initializeFirestore(app, settings)`. The fourth `options` argument of `connectFirestoreEmulator` is typed as `{ mockUserToken?: EmulatorMockTokenOptions | string }` for signature parity with the web SDK, and that shape is built from the React Native Firebase helper types `FirebaseIdToken` and `FirebaseSignInProvider`. The argument is ignored at runtime, so the emulator never receives a mock user token from this call. Sign in with Firebase Auth against the Auth emulator when your security rules depend on `request.auth`.

```js
import { Platform } from 'react-native';
import { getApp } from '@react-native-firebase/app';
import { connectFirestoreEmulator, getFirestore } from '@react-native-firebase/firestore';

const app = getApp();
const db = getFirestore(app);
const host = Platform.OS === 'android' ? '10.0.2.2' : '127.0.0.1';
connectFirestoreEmulator(db, host, 8080);
console.log('Firestore emulator configured for', host);
```

## Logging

`setLogLevel` controls Firestore SDK log verbosity. On React Native the supported levels are `debug`, `error`, and `silent` (the native logging bridge does not expose web's `verbose` / `info` / `warn`). Any other value throws.

```js
import { setLogLevel } from '@react-native-firebase/firestore';

setLogLevel('debug');
```

## Collections & Documents

Cloud Firestore stores data within "documents", which are contained within "collections", and documents can also contain
collections. For example, we could store a list of our users documents within a "Users" collection. The `collection` function
allows us to reference a collection within our code:

```js
import { collection, getFirestore } from '@react-native-firebase/firestore';

const db = getFirestore();
const usersCollection = collection(db, 'Users');
console.log('Users collection path:', usersCollection.path);
```

Pass a `FirebaseApp` (or a database id string) when you need a non-default app or a named database:

```js
import { getApp } from '@react-native-firebase/app';
import { collection, getFirestore } from '@react-native-firebase/firestore';

const secondary = getFirestore(getApp(), 'ecommerce');
const products = collection(secondary, 'Products');
console.log('Named database collection path:', products.path);
```

The `collection` function returns a [`CollectionReference`](https://reference.rnfirebase.io/_react-native-firebase/firestore/types/firestore/CollectionReference.html) class, which provides
properties and methods to query and fetch the data from Cloud Firestore. We can also directly reference a single document
on the collection by calling the `doc` function:

```js
import { collection, doc, getFirestore } from '@react-native-firebase/firestore';

const db = getFirestore();

// Get user document with an ID of ABC
const userDocument = doc(collection(db, 'Users'), 'ABC');
// Or pass path segments directly: doc(db, 'Users', 'ABC')
const sameUser = doc(db, 'Users', 'ABC');
console.log('User document path:', userDocument.path, sameUser.path);
```

The `doc` function returns a [`DocumentReference`](https://reference.rnfirebase.io/_react-native-firebase/firestore/types/firestore/DocumentReference.html).

Calling `doc` on a `CollectionReference` without a path generates a random document id on the client without any network call. `addDoc` uses the same mechanism. To reach a subcollection, pass a `DocumentReference` as the parent of `collection`, or pass every path segment:

```js
import { collection, doc, getFirestore } from '@react-native-firebase/firestore';

const db = getFirestore();
const newUserRef = doc(collection(db, 'Users'));
const ordersRef = collection(doc(db, 'Users', 'ABC'), 'orders');
const sameOrdersRef = collection(db, 'Users', 'ABC', 'orders');
console.log('Generated id:', newUserRef.id, 'Orders path:', ordersRef.path, sameOrdersRef.path);
```

Use `collectionGroup` to query every collection with the same id (for example every `messages` subcollection under every parent document):

```js
import {
  collectionGroup,
  getDocs,
  getFirestore,
  query,
  where,
} from '@react-native-firebase/firestore';

const db = getFirestore();
const snapshot = await getDocs(query(collectionGroup(db, 'messages'), where('urgent', '==', true)));
console.log('Urgent messages across collection group:', snapshot.size);
```

A document can contain different types of data, including scalar values (strings, booleans, numbers), arrays (lists) and
objects (maps) along with specific Cloud Firestore data such as `Timestamp`, `GeoPoint`, `Bytes`, and vector fields via `vector()`. The [field values](#field-values) section shows how to write each of them.

Collection and document paths must alternate: a collection path has an odd number of segments (`Users`, `Users/ABC/orders`) and a document path has an even number (`Users/ABC`). `collection()` throws for a path that points to a document, and `doc()` throws for a path that points to a collection. `collectionGroup()` takes a single collection id and throws if it contains `/`.

## Read Data

Cloud Firestore provides the ability to read the value of a collection or document. This can be read one-time, or provide
realtime updates when the data within a query changes.

### One-time read

To read a collection or document once, call `getDocs` on a [`CollectionReference`](https://reference.rnfirebase.io/_react-native-firebase/firestore/types/firestore/CollectionReference.html)
or `getDoc` on a [`DocumentReference`](https://reference.rnfirebase.io/_react-native-firebase/firestore/types/firestore/DocumentReference.html):

```js
import { collection, doc, getDoc, getDocs, getFirestore } from '@react-native-firebase/firestore';

const db = getFirestore();
const users = await getDocs(collection(db, 'Users'));
const user = await getDoc(doc(collection(db, 'Users'), 'ABC'));
console.log('Users size:', users.size, 'User exists:', user.exists());
```

#### Source options (cache vs server)

By default `getDoc` / `getDocs` try the server and fall back to the local cache when offline. Force a source with the dedicated helpers:

```js
import {
  collection,
  doc,
  getDocFromCache,
  getDocFromServer,
  getDocsFromCache,
  getDocsFromServer,
  getFirestore,
} from '@react-native-firebase/firestore';

const db = getFirestore();
const userRef = doc(db, 'Users', 'ABC');

const fromServer = await getDocFromServer(userRef);
const fromCache = await getDocFromCache(userRef);
const usersFromServer = await getDocsFromServer(collection(db, 'Users'));
const usersFromCache = await getDocsFromCache(collection(db, 'Users'));
console.log(
  'Server exists:',
  fromServer.exists(),
  'Cache exists:',
  fromCache.exists(),
  'Server size:',
  usersFromServer.size,
  'Cache size:',
  usersFromCache.size,
);
```

The native SDK decides what a cache read returns, and a cache-only read can reject when the requested data is not in the cache, so wrap `getDocFromCache` and `getDocsFromCache` in `try`/`catch` when the data may not have been fetched before.

### Realtime changes

To setup an active listener to react to any changes to the query, call `onSnapshot` with a success callback and an error callback.
For example, to watch the entire "Users" collection for when any documents are changed (removed, added, modified):

```js
import { collection, getFirestore, onSnapshot } from '@react-native-firebase/firestore';

const db = getFirestore();

function onResult(querySnapshot) {
  console.log('Got Users collection result. Size:', querySnapshot.size);
}

function onError(error) {
  console.error(error);
}

const unsubscribe = onSnapshot(collection(db, 'Users'), onResult, onError);
unsubscribe();
```

Always pass an error callback. Listener errors (for example `firestore/permission-denied`) are delivered only to the error callback (or `observer.error` on an observer object such as `{ next, error }`), and the success callback only receives snapshots, so a lone success callback is never called with an error. When no error handler is given, the error is logged with `console.error`; unlike firebase-js-sdk, `setLogLevel('silent')` does not suppress this log. The error passed to the error callback also has a `code` property such as `firestore/permission-denied` (see [Handling errors](#handling-errors)). The optional completion callback and the `complete` observer field are accepted for web SDK signature parity and are never called, because listeners do not complete.

`onSnapshot` also returns a function, allowing you to unsubscribe from events. This can be used within any
`useEffect` hooks to automatically unsubscribe when the hook needs to unsubscribe itself:

```js
import { useEffect } from 'react';
import { collection, doc, getFirestore, onSnapshot } from '@react-native-firebase/firestore';

const db = getFirestore();

function User({ userId }) {
  useEffect(() => {
    const subscriber = onSnapshot(
      doc(collection(db, 'Users'), userId),
      documentSnapshot => {
        console.log('User data: ', documentSnapshot.data());
      },
      error => {
        console.error('User listener failed:', error.message);
      },
    );

    // Stop listening for updates when no longer required
    return () => subscriber();
  }, [userId]);

  return null;
}
```

Realtime changes via `onSnapshot` can be applied to both collections and documents. Each listener holds a native resource until you call the returned function, so always unsubscribe when the component is removed from the screen.

#### Listener options

Pass an options object as the second argument (before the callbacks) to change what a listener reports:

{/* prettier-ignore */}
| Option | Values | Effect |
| --- | --- | --- |
| `includeMetadataChanges` | `true`, `false` (default) | Also fire when only `snapshot.metadata` changes (for example `fromCache` or `hasPendingWrites`) |
| `source` | `'default'` (default), `'cache'` | `'cache'` listens to the local cache only and never reads from the server |

Any other `source` value throws, and `includeMetadataChanges` must be a boolean.

#### Metadata changes and document diffs

Pass `{ includeMetadataChanges: true }` when you need events for cache-vs-server metadata flips. Use `docChanges()` to see which documents were added, modified, or removed since the previous snapshot:

```js
import {
  collection,
  getFirestore,
  onSnapshot,
  query,
  where,
} from '@react-native-firebase/firestore';

const db = getFirestore();
const unsubscribe = onSnapshot(
  query(collection(db, 'Users'), where('active', '==', true)),
  { includeMetadataChanges: true },
  snapshot => {
    snapshot.docChanges().forEach(change => {
      console.log(change.type, change.doc.id, 'fromCache:', snapshot.metadata.fromCache);
    });
  },
  error => {
    console.error('Users listener failed:', error.message);
  },
);

unsubscribe();
```

`change.type` is `'added'`, `'modified'`, or `'removed'`, and `change.oldIndex` / `change.newIndex` give the position of the document before and after the change. `docChanges()` leaves out changes that only affect metadata; call `snapshot.docChanges({ includeMetadataChanges: true })` to include them. That call throws when the listener itself was not registered with `includeMetadataChanges: true`, and on a snapshot returned by `getDocs` it always returns every change.

Listen to the local cache only with `source: 'cache'`:

```js
import { collection, getFirestore, onSnapshot } from '@react-native-firebase/firestore';

const db = getFirestore();
const unsubscribe = onSnapshot(
  collection(db, 'Users'),
  { source: 'cache' },
  snapshot => {
    console.log('Cached users:', snapshot.size, 'fromCache:', snapshot.metadata.fromCache);
  },
  error => {
    console.error('Cache listener failed:', error.message);
  },
);

unsubscribe();
```

#### Snapshots in sync

`onSnapshotsInSync` fires when all currently active listeners have caught up with the server (useful after a burst of local writes):

```js
import { getFirestore, onSnapshotsInSync } from '@react-native-firebase/firestore';

const db = getFirestore();
const unsubscribe = onSnapshotsInSync(db, () => {
  console.log('All listeners are in sync with the server');
});

unsubscribe();
```

### Snapshots

Once a query has returned a result, Firestore returns either a [`QuerySnapshot`](https://reference.rnfirebase.io/_react-native-firebase/firestore/types/firestore/QuerySnapshot.html) (for
collection queries) or a [`DocumentSnapshot`](https://reference.rnfirebase.io/_react-native-firebase/firestore/types/firestore/DocumentSnapshot.html) (for document queries). These snapshots
provide the ability to view the data, view query metadata (such as whether the data was from local cache), whether the
document exists or not and more.

#### `QuerySnapshot`

A [`QuerySnapshot`](https://reference.rnfirebase.io/_react-native-firebase/firestore/types/firestore/QuerySnapshot.html) returned from a collection query allows you to inspect the collection,
such as how many documents exist within it, access to the documents within the collection, any changes since the last query
and more.

To access the documents within a `QuerySnapshot`, call the `forEach` method:

```js
import { collection, getDocs, getFirestore } from '@react-native-firebase/firestore';

const db = getFirestore();

getDocs(collection(db, 'Users')).then(querySnapshot => {
  console.log('Total users: ', querySnapshot.size);

  querySnapshot.forEach(documentSnapshot => {
    console.log('User ID: ', documentSnapshot.id, documentSnapshot.data());
  });
});
```

Each child document of a `QuerySnapshot` is a [`QueryDocumentSnapshot`](https://reference.rnfirebase.io/_react-native-firebase/firestore/types/firestore/QueryDocumentSnapshot.html), which
allows you to access specific information about a document (see below).

#### `DocumentSnapshot`

A [`DocumentSnapshot`](https://reference.rnfirebase.io/_react-native-firebase/firestore/types/firestore/DocumentSnapshot.html) is returned from a query to a specific document, or as part
of the documents returned via a [`QuerySnapshot`](https://reference.rnfirebase.io/_react-native-firebase/firestore/types/firestore/QuerySnapshot.html). The snapshot provides the ability
to view a documents data, metadata and whether a document actually exists.

To view a documents data, call the `data` method on the snapshot:

```js
import { collection, doc, getDoc, getFirestore } from '@react-native-firebase/firestore';

const db = getFirestore();

getDoc(doc(collection(db, 'Users'), 'ABC')).then(documentSnapshot => {
  console.log('User exists: ', documentSnapshot.exists());

  if (documentSnapshot.exists()) {
    console.log('User data: ', documentSnapshot.data());
  }
});
```

A snapshot also provides a helper function to easily access deeply nested data within a document. Call the `get` method
with a dot-notated path:

```js
import { collection, doc, getDoc, getFirestore } from '@react-native-firebase/firestore';

const db = getFirestore();

function getUserZipCode(documentSnapshot) {
  return documentSnapshot.get('info.address.zipcode');
}

getDoc(doc(collection(db, 'Users'), 'ABC'))
  .then(documentSnapshot => getUserZipCode(documentSnapshot))
  .then(zipCode => {
    console.log('Users zip code is: ', zipCode);
  });
```

`get` also accepts a `FieldPath` (see [Field paths](#field-paths)). `data()` returns `undefined` when the document does not exist, so check `exists()` first; on a `QueryDocumentSnapshot` (the documents inside a `QuerySnapshot`) `data()` always returns an object.

A snapshot of a document with a pending `serverTimestamp()` write reports that field as `null` until the server confirms it. Pass `serverTimestamps` to `data()` or `get()` to choose what a pending timestamp reads as: `'estimate'` (a local estimate), `'previous'` (the previous value of the field), or `'none'` (`null`):

```js
import { collection, doc, getFirestore, onSnapshot } from '@react-native-firebase/firestore';

const db = getFirestore();
const unsubscribe = onSnapshot(
  doc(collection(db, 'Posts'), 'ABC'),
  postSnapshot => {
    const post = postSnapshot.data({ serverTimestamps: 'estimate' });
    console.log('Created at:', post?.createdAt, 'pending:', postSnapshot.metadata.hasPendingWrites);
  },
  error => {
    console.error(error);
  },
);

unsubscribe();
```

Snapshot properties at a glance:

{/* prettier-ignore */}
| Snapshot | Members |
| --- | --- |
| `DocumentSnapshot` | `id`, `ref`, `metadata`, `exists()`, `data(options)`, `get(fieldPath, options)` |
| `QuerySnapshot` | `docs`, `size`, `empty`, `metadata`, `query`, `forEach(callback)`, `docChanges(options)` |
| `SnapshotMetadata` | `fromCache` (data came from the local cache), `hasPendingWrites` (local writes not yet acknowledged by the backend) |

### Querying

Cloud Firestore offers advanced capabilities for querying collections.

#### Filtering

To filter documents within a collection, pass `where` constraints to `query`. Supported operators are `==`, `!=`, `<`, `<=`, `>`, `>=`, `array-contains`, `array-contains-any`, `in`, and `not-in`; any other operator string throws. The value cannot be `undefined`, and `null` is only allowed with `==` and `!=`. For example, to filter users where their age is greater or equal than 18 years old:

```js
import { collection, getDocs, getFirestore, query, where } from '@react-native-firebase/firestore';

const db = getFirestore();

getDocs(query(collection(db, 'Users'), where('age', '>=', 18))).then(querySnapshot => {
  querySnapshot.forEach(documentSnapshot => {
    console.log(documentSnapshot.id, documentSnapshot.data());
  });
});
```

Use the `in` operator to match documents whose field equals any value in a list. `in`, `not-in`, and `array-contains-any` require a non-empty array. `in` and `array-contains-any` allow at most 30 elements and `not-in` allows at most 10 (React Native Firebase checks this before sending the query). For example, to filter users whose `language` field is English (`en`) or French (`fr`):

```js
import { collection, getDocs, getFirestore, query, where } from '@react-native-firebase/firestore';

const db = getFirestore();

getDocs(query(collection(db, 'Users'), where('language', 'in', ['en', 'fr']))).then(
  querySnapshot => {
    querySnapshot.forEach(documentSnapshot => {
      console.log(documentSnapshot.id, documentSnapshot.data());
    });
  },
);
```

To learn more about all of the querying capabilities Cloud Firestore has to offer, view the
[Firebase documentation](https://firebase.google.com/docs/firestore/query-data/queries).

Passing several `where` constraints to `query` combines them with logical AND. Use the `and()` and `or()` composite constraints to nest AND groups inside OR groups, or the reverse.
For example:

```js
import { collection, getDocs, getFirestore, query, where } from '@react-native-firebase/firestore';

const db = getFirestore();

const snapshot = await getDocs(
  query(
    collection(db, 'Users'),
    where('user', '==', 'Tim'),
    where('email', '==', 'tim@example.com'),
  ),
);
console.log('Matched users:', snapshot.size);
```

You can use the `and()` function to make logical AND queries:

```js
import {
  and,
  collection,
  getDocs,
  getFirestore,
  query,
  where,
} from '@react-native-firebase/firestore';

const db = getFirestore();

const snapshot = await getDocs(
  query(
    collection(db, 'Users'),
    and(where('user', '==', 'Tim'), where('email', '==', 'tim@example.com')),
  ),
);
console.log('Matched users with and():', snapshot.size);
```

You can use the `or()` function to make logical OR queries:

```js
import {
  and,
  collection,
  getDocs,
  getFirestore,
  or,
  query,
  where,
} from '@react-native-firebase/firestore';

const db = getFirestore();

const snapshot = await getDocs(
  query(
    collection(db, 'Users'),
    or(
      and(where('user', '==', 'Tim'), where('email', '==', 'tim@example.com')),
      and(where('user', '==', 'Dave'), where('email', '==', 'dave@example.com')),
    ),
  ),
);
console.log('Matched users with or():', snapshot.size);
```

`Filter` is a React Native Firebase helper for building field and composite filters (`Filter(...)`, `Filter.and(...)`, `Filter.or(...)`) that you pass to the `where` method of a `CollectionReference` or `Query`. The modular `where` constraint is typed for the `(field, operator, value)` form only, so prefer `where` / `and` / `or` with `query`, and use `Filter` when you need the method style:

```js
import { Filter, collection, getDocs, getFirestore } from '@react-native-firebase/firestore';

const db = getFirestore();
const adultActive = Filter.and(Filter('age', '>=', 18), Filter('active', '==', true));
const adultOrAdmin = Filter.or(Filter('age', '>=', 18), Filter('role', '==', 'admin'));
const activeAdults = await getDocs(collection(db, 'Users').where(adultActive));
const adultsOrAdmins = await getDocs(collection(db, 'Users').where(adultOrAdmin));
console.log('Filter helper matches:', activeAdults.size, adultsOrAdmins.size);
```

`Filter.and` and `Filter.or` take between 1 and 10 `Filter` instances, and `Filter.or` throws when one of its arguments already contains an OR.

Other `where` operators include `!=`, `not-in`, `array-contains`, `array-contains-any`, and filtering by document id with `documentId()` (which compares against the document id rather than a stored field):

```js
import {
  collection,
  documentId,
  getDocs,
  getFirestore,
  query,
  where,
} from '@react-native-firebase/firestore';

const db = getFirestore();
const byId = await getDocs(
  query(collection(db, 'Users'), where(documentId(), 'in', ['ABC', 'DEF'])),
);
const withToken = await getDocs(
  query(collection(db, 'Users'), where('fcmTokens', 'array-contains', 'ABCDE123456')),
);
const withAnyToken = await getDocs(
  query(collection(db, 'Users'), where('fcmTokens', 'array-contains-any', ['A1', 'B2'])),
);
const notBanned = await getDocs(query(collection(db, 'Users'), where('status', '!=', 'banned')));
const notGuests = await getDocs(
  query(collection(db, 'Users'), where('role', 'not-in', ['guest', 'anonymous'])),
);
console.log(
  'By id:',
  byId.size,
  'With token:',
  withToken.size,
  'With any token:',
  withAnyToken.size,
  'Not banned:',
  notBanned.size,
  'Not guests:',
  notGuests.size,
);
```

Queries that combine filters or sort orders on different fields can need a composite index (see the [Firestore index overview](https://firebase.google.com/docs/firestore/query-data/index-overview)). When a required index is missing, the rejection carries the code `firestore/failed-precondition`, and the native message includes a link that opens the index creation page in the Firebase console. See [Handling errors](#handling-errors).

#### Limiting

To limit the number of documents returned from a query, use the `limit` constraint:

```js
import {
  collection,
  getDocs,
  getFirestore,
  limit,
  query,
  where,
} from '@react-native-firebase/firestore';

const db = getFirestore();

getDocs(query(collection(db, 'Users'), where('age', '>=', 18), limit(20))).then(querySnapshot => {
  querySnapshot.forEach(documentSnapshot => {
    console.log(documentSnapshot.id, documentSnapshot.data());
  });
});
```

The above example both filters the users by age and limits the documents returned to 20.

`limit` and `limitToLast` take a positive integer. `limitToLast` returns the last N results of an ordered query. It requires at least one `orderBy`; without one, the query throws when you run it with `getDocs` or `onSnapshot`:

```js
import {
  collection,
  getDocs,
  getFirestore,
  limitToLast,
  orderBy,
  query,
} from '@react-native-firebase/firestore';

const db = getFirestore();
const snapshot = await getDocs(
  query(collection(db, 'Users'), orderBy('age', 'asc'), limitToLast(5)),
);
console.log('Five oldest users:', snapshot.size);
```

#### Ordering

To order the documents by a specific value, use the `orderBy` constraint:

```js
import {
  collection,
  getDocs,
  getFirestore,
  orderBy,
  query,
} from '@react-native-firebase/firestore';

const db = getFirestore();

getDocs(query(collection(db, 'Users'), orderBy('age', 'desc'))).then(querySnapshot => {
  querySnapshot.forEach(documentSnapshot => {
    console.log(documentSnapshot.id, documentSnapshot.data());
  });
});
```

The above example orders all users in the snapshot by age in descending order. The direction is `'asc'` (default) or `'desc'`; any other value throws. `orderBy` also accepts a `FieldPath`. Documents that do not contain the ordered field are left out of the result, because ordering by a field implies the field exists.

#### Start/End

To start and/or end the query at a specific point within the collection, you can pass either a value to `startAt`,
`endAt`, `startAfter` or `endBefore`. You must specify an order to use pointers, and you cannot pass more cursor values than there are `orderBy` clauses (the query throws otherwise). The cursors follow the sort direction, so with a descending order `startAt` takes the larger value and `endAt` the smaller one. For example:

```js
import {
  collection,
  endAt,
  getDocs,
  getFirestore,
  orderBy,
  query,
  startAt,
} from '@react-native-firebase/firestore';

const db = getFirestore();

getDocs(query(collection(db, 'Users'), orderBy('age', 'desc'), startAt(30), endAt(18))).then(
  querySnapshot => {
    querySnapshot.forEach(documentSnapshot => {
      console.log(documentSnapshot.id, documentSnapshot.data());
    });
  },
);
```

The above query orders the users by age in descending order, but only returns users whose age is between 30 and 18 (inclusive).

You can further specify a [`DocumentSnapshot`](https://reference.rnfirebase.io/_react-native-firebase/firestore/types/firestore/DocumentSnapshot.html) instead of a specific value. For example:

```js
import {
  collection,
  doc,
  getDoc,
  getDocs,
  getFirestore,
  orderBy,
  query,
  startAt,
} from '@react-native-firebase/firestore';

const db = getFirestore();
const userDocumentSnapshot = await getDoc(doc(collection(db, 'Users'), 'DEF'));

getDocs(query(collection(db, 'Users'), orderBy('age', 'desc'), startAt(userDocumentSnapshot))).then(
  querySnapshot => {
    querySnapshot.forEach(documentSnapshot => {
      console.log(documentSnapshot.id, documentSnapshot.data());
    });
  },
);
```

The above query orders the users by age in descending order, however only returns documents whose order starts at the user
with an ID of `DEF`. The snapshot must exist and must contain every field used in `orderBy`; otherwise the query throws. React Native Firebase adds the document id as a final tie-breaking sort for snapshot cursors. For pagination built on these cursors, see [Implementing Pagination](/firestore/pagination).

`startAfter` / `endBefore` exclude the boundary document or value:

```js
import {
  collection,
  endBefore,
  getDocs,
  getFirestore,
  orderBy,
  query,
  startAfter,
} from '@react-native-firebase/firestore';

const db = getFirestore();
const snapshot = await getDocs(
  query(collection(db, 'Users'), orderBy('age', 'asc'), startAfter(18), endBefore(65)),
);
console.log('Ages after 18 and before 65:', snapshot.size);
```

#### Query equality helpers

`refEqual`, `queryEqual`, and `snapshotEqual` compare references, queries, and snapshots for equality:

```js
import {
  collection,
  doc,
  getDoc,
  getFirestore,
  query,
  queryEqual,
  refEqual,
  snapshotEqual,
  where,
} from '@react-native-firebase/firestore';

const db = getFirestore();
const a = doc(db, 'Users', 'ABC');
const b = doc(collection(db, 'Users'), 'ABC');
console.log('Same ref:', refEqual(a, b));

const q1 = query(collection(db, 'Users'), where('age', '>=', 18));
const q2 = query(collection(db, 'Users'), where('age', '>=', 18));
console.log('Same query:', queryEqual(q1, q2));

const snap1 = await getDoc(a);
const snap2 = await getDoc(b);
console.log('Same snapshot data:', snapshotEqual(snap1, snap2));
```

`queryEqual` compares two queries (collection, filters, order, limits), `refEqual` compares two document or collection references, and `snapshotEqual` compares two snapshots (same data, metadata, and reference). Each throws when given a value of the wrong type.

#### Field paths

A string field path uses dots to reach nested map fields (`'info.address.zipcode'`). When a key itself contains a dot, build a `FieldPath` from its segments instead. `FieldPath` is accepted by `where`, `orderBy`, `snapshot.get`, the aggregate helpers (`sum`, `average`), and `mergeFields`. A string path cannot be empty, start or end with `.`, contain `..`, or contain `~`, `*`, `/`, `[`, or `]`, and a `FieldPath` needs at least one non-empty segment:

```js
import {
  FieldPath,
  collection,
  doc,
  documentId,
  getDoc,
  getDocs,
  getFirestore,
  orderBy,
  query,
  where,
} from '@react-native-firebase/firestore';

const db = getFirestore();
const zipPath = new FieldPath('info', 'address', 'zipcode');
const dottedKey = new FieldPath('settings', 'theme.color');

const inZip = await getDocs(query(collection(db, 'Users'), where(zipPath, '==', 94040)));
const byId = await getDocs(query(collection(db, 'Users'), orderBy(documentId())));
const userSnapshot = await getDoc(doc(db, 'Users', 'ABC'));
console.log('In zip:', inZip.size, 'By id:', byId.size);
console.log('Zip code:', userSnapshot.get(zipPath), 'Theme color:', userSnapshot.get(dottedKey));
console.log('Equal paths:', zipPath.isEqual(new FieldPath('info', 'address', 'zipcode')));
```

#### Query Limitations

Cloud Firestore Standard edition applies these limits to queries (see the [official query documentation](https://firebase.google.com/docs/firestore/query-data/queries#limits_on_or_queries) for the full list and for Enterprise edition differences):

- `or`, `in`, and `array-contains-any` queries are limited to 30 branches once Firestore expands the filter into a list of alternative AND groups. An `and` of several `or` groups multiplies the count.
- Each expanded branch can contain at most one `array-contains` clause, and you cannot combine `array-contains` with `array-contains-any` in the same branch.
- `not-in` cannot be combined with `in`, `array-contains-any`, `or`, or `!=`, and only one `not-in` or `!=` is allowed per query. `not-in` supports up to 10 comparison values.
- The sum of filters, sort orders, and parent path segments in a query cannot exceed 100.
- A query with an inequality filter on a field implies ordering by that field and only matches documents where the field exists.

React Native Firebase additionally rejects some invalid combinations before the query reaches the native SDK (more than one `!=`, more than one `array-contains`, `array-contains-any` or `in` together with `not-in`, and `null` with an operator other than `==` or `!=`).

## Writing Data

The [Firebase documentation](https://firebase.google.com/docs/firestore/manage-data/structure-data) provides great examples
on best practices on how to structure your data. We highly recommend reading the guide before building out your database.

For a more in-depth look at what is possible when writing data to Firestore please refer to this [documentation](https://firebase.google.com/docs/firestore/manage-data/add-data)

## Adding documents

To add a document to a collection, use `addDoc` with a [`CollectionReference`](https://reference.rnfirebase.io/_react-native-firebase/firestore/types/firestore/CollectionReference.html):

```js
import { addDoc, collection, getFirestore } from '@react-native-firebase/firestore';

const db = getFirestore();

addDoc(collection(db, 'Users'), {
  name: 'Ada Lovelace',
  age: 30,
}).then(() => {
  console.log('User added!');
});
```

`addDoc` adds the document to your collection with a random unique ID. If you'd like to specify your own ID,
call `setDoc` with a [`DocumentReference`](https://reference.rnfirebase.io/_react-native-firebase/firestore/types/firestore/DocumentReference.html) instead:

```js
import { collection, doc, getFirestore, setDoc } from '@react-native-firebase/firestore';

const db = getFirestore();

setDoc(doc(collection(db, 'Users'), 'ABC'), {
  name: 'Ada Lovelace',
  age: 30,
}).then(() => {
  console.log('User added!');
});
```

Pass `{ merge: true }` (or `{ mergeFields: [...] }`) when you want `setDoc` to merge into an existing document instead of overwriting it. `merge` must be a boolean, `mergeFields` is an array of dot-separated field paths or `FieldPath` instances, and passing both in the same call throws:

```js
import { doc, getFirestore, setDoc } from '@react-native-firebase/firestore';

const db = getFirestore();
await setDoc(doc(db, 'Users', 'ABC'), { age: 31 }, { merge: true });
await setDoc(
  doc(db, 'Users', 'ABC'),
  { age: 32, name: 'Ignored by mergeFields' },
  { mergeFields: ['age'] },
);
console.log('User merged!');
```

Document data cannot contain `undefined` values. Writing one fails with `Unsupported field value: undefined`, which also applies to `addDoc`, `updateDoc`, transactions, and batches. Remove the key, use `deleteField()` with `updateDoc`, or enable `ignoreUndefinedProperties` in [Settings](#settings).

### Updating documents

The `setDoc` example above replaces any existing data on a given [`DocumentReference`](https://reference.rnfirebase.io/_react-native-firebase/firestore/types/firestore/DocumentReference.html).
if you'd like to update a document instead, use `updateDoc`:

```js
import { collection, doc, getFirestore, updateDoc } from '@react-native-firebase/firestore';

const db = getFirestore();

updateDoc(doc(collection(db, 'Users'), 'ABC'), {
  age: 31,
}).then(() => {
  console.log('User updated!');
});
```

`updateDoc` fails with `firestore/not-found` when the document does not exist; use `setDoc` with `{ merge: true }` to create it when it might be missing. Pass a single object of fields to update. The method also provides support for updating deeply nested values via dot-notation:

```js
import { collection, doc, getFirestore, updateDoc } from '@react-native-firebase/firestore';

const db = getFirestore();

updateDoc(doc(collection(db, 'Users'), 'ABC'), {
  'info.address.zipcode': 94040,
}).then(() => {
  console.log('User updated!');
});
```

#### Field values

Cloud Firestore supports storing and manipulating values on your database, such as `Timestamp`, `GeoPoint`, `Bytes`, vectors, and array management.

To store `GeoPoint` values, provide the latitude and longitude to an instance of the
class. Latitude must be between -90 and 90 and longitude between -180 and 180, otherwise the constructor throws:

```js
import { doc, GeoPoint, getFirestore, updateDoc } from '@react-native-firebase/firestore';

const db = getFirestore();

updateDoc(doc(db, 'users', 'ABC'), {
  'info.address.location': new GeoPoint(53.483959, -2.244644),
}).then(() => {
  console.log('GeoPoint updated!');
});
```

To store raw `Bytes` (for example of a `Base64` image string), provide the string to the static
`fromBase64String` method on the class (the string must be non-empty), or build the value from a `Uint8Array` with `Bytes.fromUint8Array`. Read it back with `toBase64()` or `toUint8Array()`:

```js
import { Bytes, doc, getFirestore, updateDoc } from '@react-native-firebase/firestore';

const db = getFirestore();

updateDoc(doc(db, 'users', 'ABC'), {
  'info.avatar': Bytes.fromBase64String('iVBORw0KGgo='),
  'info.thumbnail': Bytes.fromUint8Array(new Uint8Array([1, 2, 3])),
}).then(() => {
  console.log('Bytes updated!');
});
```

When storing timestamps, it is recommended you use `serverTimestamp()`. When written to the database, the Firebase servers will write a timestamp based on their time, rather than the clients. This helps
resolve any data consistency issues with different client timezones:

```js
import { doc, getFirestore, serverTimestamp, updateDoc } from '@react-native-firebase/firestore';

const db = getFirestore();

updateDoc(doc(db, 'users', 'ABC'), {
  createdAt: serverTimestamp(),
}).then(() => {
  console.log('Timestamp updated!');
});
```

Cloud Firestore also allows for storing arrays. To help manage the values with an array (adding or removing), the API
exposes `arrayUnion` and `arrayRemove` helpers.

To add a value to an array (if value does not exist, will not add duplicate values):

```js
import { arrayUnion, doc, getFirestore, updateDoc } from '@react-native-firebase/firestore';

const db = getFirestore();

updateDoc(doc(db, 'users', 'ABC'), {
  fcmTokens: arrayUnion('ABCDE123456'),
}).then(() => {
  console.log('Array union applied!');
});
```

To remove a value from the array (if the value exists):

```js
import { arrayRemove, doc, getFirestore, updateDoc } from '@react-native-firebase/firestore';

const db = getFirestore();

updateDoc(doc(db, 'users', 'ABC'), {
  fcmTokens: arrayRemove('ABCDE123456'),
}).then(() => {
  console.log('Array remove applied!');
});
```

`increment` atomically bumps a numeric field on the server (often simpler than a transaction when you only need a counter):

```js
import { doc, getFirestore, increment, updateDoc } from '@react-native-firebase/firestore';

const db = getFirestore();
await updateDoc(doc(db, 'posts', 'ABC'), {
  likes: increment(1),
});
console.log('likes incremented');
```

Use the `Timestamp` class when you need a client-side timestamp value (as opposed to `serverTimestamp()`). Build it with `Timestamp.now()`, `Timestamp.fromDate(date)`, `Timestamp.fromMillis(ms)`, or `new Timestamp(seconds, nanoseconds)`, and convert back with `toDate()` or `toMillis()`. The constructor throws for out-of-range values:

```js
import { Timestamp, doc, getFirestore, updateDoc } from '@react-native-firebase/firestore';

const db = getFirestore();
await updateDoc(doc(db, 'users', 'ABC'), {
  lastSeen: Timestamp.now(),
  born: Timestamp.fromDate(new Date('1815-12-10')),
  checkedAt: Timestamp.fromMillis(Date.now()),
});
console.log('Timestamps written');
```

Store a vector embedding with `vector()` (nearest-neighbor queries use the [Pipelines](/firestore/pipelines) `findNearest` stage on React Native Firebase):

```js
import { doc, getFirestore, setDoc, vector } from '@react-native-firebase/firestore';

const db = getFirestore();
await setDoc(doc(db, 'items', 'item1'), {
  name: 'example',
  embedding: vector([0.1, 0.2, 0.3]),
});
console.log('Vector embedding written');
```

## Removing data

You can delete documents within Cloud Firestore using the `deleteDoc` method with a [`DocumentReference`](https://reference.rnfirebase.io/_react-native-firebase/firestore/types/firestore/DocumentReference.html):

```js
import { deleteDoc, doc, getFirestore } from '@react-native-firebase/firestore';

const userDocRef = doc(getFirestore(), 'users', 'ExampleUser');
deleteDoc(userDocRef).then(() => {
  console.log('User deleted!');
});
```

The client SDK has no function that deletes a whole collection. Delete a small collection by reading its documents and deleting each one in a [batch write](#batch-write), or delete large collections from a trusted environment with a Firebase Admin SDK.

> If a document contains any sub-collections, these will not be deleted from database. You must delete
> any sub-collections yourself.

If you need to remove a specific property with a document, rather than the document itself, you can use `deleteField`:

```js
import {
  collection,
  deleteField,
  doc,
  getFirestore,
  updateDoc,
} from '@react-native-firebase/firestore';

const db = getFirestore();

updateDoc(doc(collection(db, 'Users'), 'ABC'), {
  fcmTokens: deleteField(),
}).then(() => {
  console.log('Field deleted!');
});
```

## Typed data with converters

`withConverter` attaches a converter object to a `CollectionReference`, `DocumentReference`, or `Query`. Writes through that reference (`setDoc`, `addDoc`, and `set` on a batch or transaction) call `toFirestore(model, options)` to turn your model into stored data, and reads call `fromFirestore(snapshot, options)` so `snapshot.data()` returns your model. Both functions are required; `withConverter` throws when either is missing. Inside `fromFirestore`, `snapshot.data()` returns the raw stored map. Pass `null` to remove a converter:

```js
import {
  addDoc,
  collection,
  doc,
  getDoc,
  getDocs,
  getFirestore,
  query,
  setDoc,
  where,
} from '@react-native-firebase/firestore';

class City {
  constructor(name, population) {
    this.name = name;
    this.population = population;
  }

  describe() {
    return `${this.name} (${this.population})`;
  }
}

const cityConverter = {
  toFirestore(city) {
    return { name: city.name, population: city.population };
  },
  fromFirestore(snapshot, options) {
    const data = snapshot.data(options);
    return new City(data.name, data.population);
  },
};

const db = getFirestore();
const cities = collection(db, 'cities').withConverter(cityConverter);

await setDoc(doc(cities, 'LON'), new City('London', 9000000));
await addDoc(cities, new City('Paris', 2100000));

const london = (await getDoc(doc(cities, 'LON'))).data();
console.log('Typed read:', london?.describe());

const large = await getDocs(query(cities, where('population', '>', 1000000)));
large.forEach(citySnapshot => {
  console.log('Query result:', citySnapshot.data().describe());
});

const untyped = collection(db, 'cities').withConverter(null);
console.log('Converter removed:', untyped.converter === null);
```

## Transactions

Transactions are a way to always ensure a write occurs with the information available on the server at commit time. Transactions
never partially apply writes and all writes execute at the end of a successful transaction.

Transactions are useful when you want to update a field's value based on its current value, or the value of some other field.
If you simply want to write multiple documents without using the document's current state, a [batch write](/firestore/usage#batch-write) would be more appropriate.

When using transactions, note that:

- Read operations must come before write operations.
- A function calling a transaction (transaction function) might run more than once if a concurrent edit affects a document that the transaction reads.
- Transaction functions should not directly modify application state (return a value from the `updateFunction`).
- Transactions will fail when the client is offline.
- The `updateFunction` must return a Promise (use an `async` function); otherwise `runTransaction` rejects with an error.
- `transaction.get` accepts a `DocumentReference` only. Queries cannot be read inside a transaction.
- `transaction.set`, `transaction.update`, and `transaction.delete` are buffered while your function runs and sent together once it resolves, so they return the transaction for chaining and do not return a Promise.
- If your function throws or rejects, `runTransaction` rejects with that error and nothing is written.
- Firestore ends a transaction that runs longer than 270 seconds or sits idle for 60 seconds.

Imagine a scenario whereby an app has the ability to "Like" user posts. Whenever a user presses the "Like" button,
a "likes" value (number of likes) on a "Posts" collection document increments. Without transactions, we'd first need to read
the existing value and then increment that value in two separate operations.

On a high traffic application, the value on the server could already have changed by the time the operation sets a replacement value,
causing the actual number to not be consistent.

Transactions remove this issue by atomically updating the value on the server. If the value changes whilst the transaction
is executing, it will retry. This always ensures the value on the server is used rather than the client value.

To execute a transaction, call `runTransaction`. The callback receives a `Transaction` instance. In the React Native Firebase type hierarchy that class extends `LiteTransaction` (exported for the type hierarchy; firebase-js-sdk does not export `LiteTransaction` from the public Firestore API):

```js
import { doc, getFirestore, runTransaction } from '@react-native-firebase/firestore';

const db = getFirestore();

function onPostLike(postId) {
  // Create a reference to the post
  const postReference = doc(db, 'posts', postId);

  return runTransaction(db, async transaction => {
    // Get post data first
    const postSnapshot = await transaction.get(postReference);

    if (!postSnapshot.exists()) {
      throw new Error('Post does not exist!');
    }

    const postData = postSnapshot.data();
    transaction.update(postReference, {
      likes: postData.likes + 1,
    });
  });
}

onPostLike('ABC')
  .then(() => console.log('Post likes incremented via a transaction'))
  .catch(error => console.error(error));
```

Transactions can also `set` (optionally with `{ merge: true }`) and `delete` documents. Pass `{ maxAttempts }` as the third argument to limit how many times the transaction function may run (the minimum is 1; a lower value throws):

```js
import { doc, getFirestore, runTransaction } from '@react-native-firebase/firestore';

const db = getFirestore();

async function transfer(fromId, toId, amount) {
  const fromRef = doc(db, 'accounts', fromId);
  const toRef = doc(db, 'accounts', toId);
  const pendingRef = doc(db, 'pendingTransfers', `${fromId}-${toId}`);

  return runTransaction(
    db,
    async transaction => {
      const fromSnapshot = await transaction.get(fromRef);
      const toSnapshot = await transaction.get(toRef);
      const fromBalance = fromSnapshot.data()?.balance ?? 0;
      const toBalance = toSnapshot.data()?.balance ?? 0;

      if (fromBalance < amount) {
        throw new Error('Insufficient funds');
      }

      transaction
        .update(fromRef, { balance: fromBalance - amount })
        .set(toRef, { balance: toBalance + amount }, { merge: true })
        .delete(pendingRef);

      return fromBalance - amount;
    },
    { maxAttempts: 3 },
  );
}

transfer('alice', 'bob', 10)
  .then(balance => console.log('New balance:', balance))
  .catch(error => console.error('Transfer failed:', error));
```

## Batch write

If you do not need to read any documents in your operation set, you can execute multiple write operations as a single batch
that contains any combination of `set`, `update`, or `delete` operations. A batch of writes completes atomically and can
write to multiple documents. Unlike transactions, batches are not retried and they also run while the device is offline (the writes are queued and sent when the connection returns).

First, create a batch instance via `writeBatch`, perform operations on the batch and finally commit it once ready. `set`, `update`, and `delete` return the batch for chaining, only accept references that belong to the same app as the batch, and throw once `commit()` has been called, so create a new batch for each commit:

```js
import { doc, getFirestore, serverTimestamp, writeBatch } from '@react-native-firebase/firestore';

const db = getFirestore();

async function archiveUser(userId) {
  const batch = writeBatch(db);

  batch
    .set(doc(db, 'archivedUsers', userId), { archivedAt: serverTimestamp() }, { merge: true })
    .update(doc(db, 'Users', userId), { active: false })
    .delete(doc(db, 'sessions', userId));

  await batch.commit();
}

archiveUser('ABC').then(() => console.log('User archived in a single batch.'));
```

The example below deletes every document returned by a query in one batch. A batch with hundreds of documents can exceed the transaction size limit, so split larger sets into several batches:

```js
import { collection, getDocs, getFirestore, writeBatch } from '@react-native-firebase/firestore';

const db = getFirestore();

async function massDeleteUsers() {
  // Get all users
  const usersQuerySnapshot = await getDocs(collection(db, 'Users'));

  // Create a batch instance
  const batch = writeBatch(db);

  usersQuerySnapshot.forEach(documentSnapshot => {
    batch.delete(documentSnapshot.ref);
  });

  return batch.commit();
}

massDeleteUsers().then(() => console.log('All users deleted in a single batch operation.'));
```

## Handling errors

Errors that come from the native Firestore SDK reject with an `Error` whose `code` is `firestore/` followed by the Firestore status code, and whose `message` starts with `[firestore/<code>]`. The codes are `aborted`, `already-exists`, `cancelled`, `data-loss`, `deadline-exceeded`, `failed-precondition`, `internal`, `invalid-argument`, `not-found`, `out-of-range`, `permission-denied`, `resource-exhausted`, `unauthenticated`, `unavailable`, `unimplemented`, and `unknown`. Argument validation errors thrown by React Native Firebase itself (for example an invalid `where` operator) are plain `Error` objects without a `code`.

A query that needs a composite index fails with `firestore/failed-precondition`. For that case the native message is preserved, and it typically contains a link that creates the missing index in the Firebase console:

```js
import {
  collection,
  getDocs,
  getFirestore,
  orderBy,
  query,
  where,
} from '@react-native-firebase/firestore';

const db = getFirestore();

async function loadActiveUsersByAge() {
  try {
    const snapshot = await getDocs(
      query(collection(db, 'Users'), where('active', '==', true), orderBy('age', 'desc')),
    );
    return snapshot.docs.map(userSnapshot => userSnapshot.data());
  } catch (error) {
    if (error.code === 'firestore/failed-precondition') {
      console.warn('Missing index or precondition failed:', error.message);
    } else if (error.code === 'firestore/permission-denied') {
      console.warn('Security rules rejected the read');
    } else if (error.code === 'firestore/unavailable') {
      console.warn('Backend unreachable, try again with a backoff');
    } else {
      throw error;
    }
    return [];
  }
}

loadActiveUsersByAge().then(users => console.log('Loaded users:', users.length));
```

Listeners report the same errors through the error callback of `onSnapshot`, and `runTransaction`, `writeBatch(...).commit()`, and `loadBundle` reject with them as well. A `namedQuery` call itself resolves with a `Query`; running that query fails when the name was never loaded in a bundle (`getDocs` rejects and `onSnapshot` calls its error callback).

## Secure your data

It is important that you understand how to write rules in your Firebase console to ensure that your data is secure. Please
follow the Firebase Firestore documentation on [security](https://firebase.google.com/docs/firestore/security/get-started).

## Settings

`initializeFirestore(app, settings, databaseId?)` returns a `Firestore` instance synchronously and applies `settings` in the background (through the native bridge on Android and iOS, or the firebase-js-sdk web interop on macOS). The native layer stores the values and reads them when it creates the native Firestore instance, so call `initializeFirestore` once at startup, before the first read, write, or listener for that app and database. Calling it after Firestore has started does not throw, but the new settings do not apply to the running native instance.

{/* prettier-ignore */}
| Setting | Type | Notes |
| --- | --- | --- |
| `persistence` | `boolean` | `false` disables the local cache. `getPersistentCacheIndexManager` then returns `null` |
| `cacheSizeBytes` | `number` | At least `1048576` (1 MB), or `CACHE_SIZE_UNLIMITED` to stop the SDK evicting cached documents by size |
| `host` | `string` | Non-empty host to use instead of the default backend. On Android, `localhost` and `127.0.0.1` are rewritten to `10.0.2.2` |
| `ssl` | `boolean` | Whether the connection to `host` is encrypted |
| `ignoreUndefinedProperties` | `boolean` | Defaults to `false`. When `true`, keys whose value is `undefined` are skipped on write instead of failing |
| `serverTimestampBehavior` | `'estimate'`, `'previous'`, `'none'` | Default for `snapshot.data()` when a document has a pending `serverTimestamp()` write. `'none'` (null) is used when unset |

The web-only keys `localCache`, `experimentalForceLongPolling`, `experimentalAutoDetectLongPolling`, and `experimentalLongPollingOptions` are accepted so web code type-checks, but they are not applied on Android and iOS. Persistence is controlled with `persistence` and `cacheSizeBytes` instead, and `memoryLocalCache()` / `persistentLocalCache()` are not available. Any other key, or a wrong value (for example `persistence: 'yes'` or a non-boolean `ssl`), is reported with a descriptive `console.warn` and the settings are not applied. `initializeFirestore` does not throw or return a promise for that error, so you cannot catch it with `try`/`catch`. Validate settings before you pass them.

```js
import { getApp } from '@react-native-firebase/app';
import { CACHE_SIZE_UNLIMITED, initializeFirestore } from '@react-native-firebase/firestore';

const db = initializeFirestore(getApp(), {
  cacheSizeBytes: CACHE_SIZE_UNLIMITED,
  ignoreUndefinedProperties: true,
  serverTimestampBehavior: 'estimate',
});
console.log('Firestore initialized:', Boolean(db));
```

Pass a database id as the third argument to configure a named database: `initializeFirestore(getApp(), settings, 'ecommerce')`.

## Offline Capabilities

Firestore provides out of the box support for offline capabilities. When reading and writing data, Firestore uses a local
database which synchronizes automatically with the server. Firestore functionality continues when users are offline, and
automatically handles data migration to the server when they regain connectivity.

This functionality is enabled by default on native platforms, however it can be disabled if you need it to be disabled (e.g. on apps containing
sensitive information) with the `persistence` setting from [Settings](#settings):

```js
import { getApp } from '@react-native-firebase/app';
import { initializeFirestore } from '@react-native-firebase/firestore';

const db = initializeFirestore(getApp(), {
  persistence: false, // disable offline persistence
});
console.log('Persistence disabled:', Boolean(db));
```

### Disable and enable network

`disableNetwork` forces listeners and gets to use the local cache only; queued writes flush after `enableNetwork`. `waitForPendingWrites` resolves when locally pending writes have been acknowledged by the backend:

```js
import {
  disableNetwork,
  enableNetwork,
  getFirestore,
  waitForPendingWrites,
} from '@react-native-firebase/firestore';

const db = getFirestore();
await disableNetwork(db);
console.log('Network disabled');
await enableNetwork(db);
await waitForPendingWrites(db);
console.log('Network enabled and pending writes flushed');
```

### Clear persistence and terminate

`clearPersistence` is the React Native Firebase-specific helper that clears the persistent cache for the Firestore instance (firebase-js-sdk exposes this as `clearIndexedDbPersistence` only). React Native Firebase also exports `clearIndexedDbPersistence` for naming parity with the web SDK. Both call the same native clear on iOS and Android; IndexedDB is a web concept and React Native does not use it. `clearPersistence` can fail while the instance is still running, so remove active listeners and call `terminate` first. `terminate` shuts down the native client and evicts it from the native instance cache, including its emulator registration: the next Firestore call creates a fresh native instance, and you need to call `connectFirestoreEmulator` again if you use the emulator.

```js
import { clearPersistence, getFirestore, terminate } from '@react-native-firebase/firestore';

const db = getFirestore();
await terminate(db);
await clearPersistence(db);
console.log('Instance terminated and persistence cleared');
```

`clearIndexedDbPersistence(db)` is a drop-in replacement for `clearPersistence(db)` when you share code with a web app:

```js
import {
  clearIndexedDbPersistence,
  getFirestore,
  terminate,
} from '@react-native-firebase/firestore';

const db = getFirestore();
await terminate(db);
await clearIndexedDbPersistence(db);
console.log('Persistence cleared through the web-named helper');
```

### Persistent cache indexes

With persistence enabled, `getPersistentCacheIndexManager` returns a manager for automatic local query indexes, and it returns `null` after `initializeFirestore` was called with `persistence: false`. These helpers return Promises on React Native Firebase (native IO) even though the web SDK returns `void`:

```js
import {
  deleteAllPersistentCacheIndexes,
  disablePersistentCacheIndexAutoCreation,
  enablePersistentCacheIndexAutoCreation,
  getFirestore,
  getPersistentCacheIndexManager,
} from '@react-native-firebase/firestore';

const db = getFirestore();
const indexManager = getPersistentCacheIndexManager(db);
if (indexManager) {
  await enablePersistentCacheIndexAutoCreation(indexManager);
  await disablePersistentCacheIndexAutoCreation(indexManager);
  await deleteAllPersistentCacheIndexes(indexManager);
  console.log('Persistent cache index manager exercised');
}
```

## Aggregation queries

`getCountFromServer` and `getAggregateFromServer` run server-side aggregations without downloading matching documents. Build aggregate fields with `count`, `sum`, and `average`:

```js
import {
  average,
  collection,
  count,
  getAggregateFromServer,
  getCountFromServer,
  getFirestore,
  query,
  sum,
  where,
} from '@react-native-firebase/firestore';

const db = getFirestore();
const users = query(collection(db, 'Users'), where('active', '==', true));
const countSnap = await getCountFromServer(users);
console.log('Active user count:', countSnap.data().count);

const aggregateSnap = await getAggregateFromServer(users, {
  users: count(),
  totalAge: sum('age'),
  avgAge: average('age'),
});
console.log('Aggregates:', aggregateSnap.data());
```

Both functions always query the server, so they fail without a network connection. The `aggregateSpec` must be an object with at least one aggregate field, `sum` and `average` take a field name or a `FieldPath`, and `average` resolves to `null` when there is nothing to average. Use `aggregateFieldEqual` and `aggregateQuerySnapshotEqual` to compare aggregate fields and aggregate snapshots:

```js
import {
  aggregateFieldEqual,
  aggregateQuerySnapshotEqual,
  collection,
  count,
  getAggregateFromServer,
  getFirestore,
  sum,
} from '@react-native-firebase/firestore';

const db = getFirestore();
console.log('Same field:', aggregateFieldEqual(sum('age'), sum('age')));
console.log('Different field:', aggregateFieldEqual(sum('age'), count()));

const first = await getAggregateFromServer(collection(db, 'Users'), { total: count() });
const second = await getAggregateFromServer(collection(db, 'Users'), { total: count() });
console.log('Same snapshot:', aggregateQuerySnapshotEqual(first, second));
```

## Data bundles

Cloud Firestore data bundles are static data files built by you from Cloud Firestore document and query snapshots,
and published by you on a CDN, hosting service or other solution. Once a bundle is loaded, a client app can query documents
from the local cache or the backend.

To load and query data bundles, use `loadBundle` and `namedQuery`. The bundle must be passed as a non-empty string (read it with `response.text()`); the typed `ArrayBuffer` and `ReadableStream` inputs from the web SDK are not supported:

```js
import {
  getDocsFromCache,
  getFirestore,
  loadBundle,
  namedQuery,
} from '@react-native-firebase/firestore';

const db = getFirestore();

// load the bundle contents
const response = await fetch('https://api.example.com/bundles/stories');
const bundle = await response.text();
await loadBundle(db, bundle);

// query the results from the cache
// note: use getDocsFromCache to query the local cache only
const storiesQuery = await namedQuery(db, 'stories-query');
if (storiesQuery) {
  const snapshot = await getDocsFromCache(storiesQuery);
  console.log('Cached stories:', snapshot.size);
}
```

`namedQuery` is typed as `Promise<Query | null>` for web SDK parity, but React Native Firebase always returns a `Query` object. The name is looked up natively when the query runs, so a name that was not part of a loaded bundle makes that read reject (or calls the listener's error callback), instead of resolving `null`. Wrap the read in `try`/`catch`.

`loadBundle` returns a `LoadBundleTask`, which you can `await` or observe with `onProgress(next, error, complete)`. `next` receives a `LoadBundleTaskProgress` object with `taskState`, `documentsLoaded`, `totalDocuments`, `bytesLoaded`, and `totalBytes`. Progress is reported once, when the native load finishes (`taskState` `'Success'`); on failure `next` receives `taskState` `'Error'` before the `error` callback runs, and awaiting the task rejects:

```js
import { getFirestore, loadBundle } from '@react-native-firebase/firestore';

const db = getFirestore();
const response = await fetch('https://api.example.com/bundles/stories');
const bundle = await response.text();

const task = loadBundle(db, bundle);
task.onProgress(
  progress => {
    console.log(progress.taskState, progress.documentsLoaded, '/', progress.totalDocuments);
  },
  error => {
    console.error('Bundle failed:', error.message);
  },
  () => {
    console.log('Bundle loaded');
  },
);

try {
  const finalProgress = await task;
  console.log('Bytes loaded:', finalProgress.bytesLoaded, 'of', finalProgress.totalBytes);
} catch (error) {
  console.error('loadBundle rejected:', error);
}
```

You can build data bundles with the Admin SDK. For more information about building and serving data bundles, see Firebase Firestore main documentation on [Data bundles](https://firebase.google.com/docs/firestore/bundles) as well as their "[Bundle Solutions](https://firebase.google.com/docs/firestore/solutions/serve-bundles)" page.

## Exported classes and types

The package also exports these classes. You normally receive instances from the functions above rather than constructing them, and you can use them with `instanceof` checks or as TypeScript types:

{/* prettier-ignore */}
| Export | Returned by or used for |
| --- | --- |
| `Firestore` | `getFirestore()` and `initializeFirestore()` |
| `CollectionReference`, `DocumentReference` | `collection()` and `doc()` |
| `DocumentSnapshot`, `QueryDocumentSnapshot`, `QuerySnapshot`, `SnapshotMetadata` | Results of `getDoc`, `getDocs`, and `onSnapshot` |
| `Transaction`, `WriteBatch` | The `runTransaction` callback argument and `writeBatch()` |
| `LoadBundleTask` | `loadBundle()` |
| `AggregateField`, `AggregateQuerySnapshot` | `count()`, `sum()`, `average()` and the results of `getCountFromServer` and `getAggregateFromServer` |
| `FieldValue` | `serverTimestamp()`, `increment()`, `arrayUnion()`, `arrayRemove()`, and `deleteField()` |
| `VectorValue` | `vector()` |
| `QueryConstraint`, `QueryFieldFilterConstraint`, `QueryCompositeFilterConstraint`, `QueryOrderByConstraint`, `QueryLimitConstraint`, `QueryStartAtConstraint`, `QueryEndAtConstraint` | `where()`, `and()`, `or()`, `orderBy()`, `limit()`, `limitToLast()`, `startAt()`, `startAfter()`, `endAt()`, and `endBefore()` |

## Package version

`SDK_VERSION` is the React Native Firebase Firestore package version string exported from `@react-native-firebase/firestore`. The firebase-js-sdk does not export `SDK_VERSION` from `@firebase/firestore`.

```js
import { SDK_VERSION } from '@react-native-firebase/firestore';

console.log('Firestore package version:', SDK_VERSION);
```
