0
# Database Operations
1
2
Core database functionality for accessing collections and documents, with full CRUD operations and real-time synchronization.
3
4
## Capabilities
5
6
### Main Firestore Instance
7
8
Get the default Firestore instance or initialize with specific database ID.
9
10
```typescript { .api }
11
/**
12
* Get the default Firestore instance
13
* @returns Firestore module instance
14
*/
15
firestore(): FirebaseFirestoreTypes.Module;
16
17
/**
18
* Get Firestore instance for specific database
19
* @param databaseId - Optional database identifier
20
* @returns Firestore module instance
21
*/
22
firestore(databaseId?: string): FirebaseFirestoreTypes.Module;
23
```
24
25
**Usage Examples:**
26
27
```typescript
28
import firestore from '@react-native-firebase/firestore';
29
30
// Default database
31
const db = firestore();
32
33
// Specific database
34
const customDb = firestore('custom-database');
35
```
36
37
### Collection References
38
39
Access collections within the Firestore database.
40
41
```typescript { .api }
42
/**
43
* Get a reference to a collection
44
* @param collectionPath - Path to the collection
45
* @returns CollectionReference instance
46
*/
47
collection(collectionPath: string): FirebaseFirestoreTypes.CollectionReference;
48
49
/**
50
* Query across collection groups with the same ID
51
* @param collectionId - Collection identifier to query across
52
* @returns Query instance for collection group
53
*/
54
collectionGroup(collectionId: string): FirebaseFirestoreTypes.Query;
55
56
interface CollectionReference<T = FirebaseFirestoreTypes.DocumentData> extends Query<T> {
57
readonly id: string;
58
readonly parent: FirebaseFirestoreTypes.DocumentReference | null;
59
readonly path: string;
60
61
/**
62
* Add a new document to the collection
63
* @param data - Document data to add
64
* @returns Promise resolving to the new document reference
65
*/
66
add(data: T): Promise<FirebaseFirestoreTypes.DocumentReference<T>>;
67
68
/**
69
* Get a document reference within this collection
70
* @param documentPath - Optional document path
71
* @returns Document reference
72
*/
73
doc(documentPath?: string): FirebaseFirestoreTypes.DocumentReference<T>;
74
}
75
```
76
77
**Usage Examples:**
78
79
```typescript
80
import firestore from '@react-native-firebase/firestore';
81
82
// Get collection reference
83
const usersCollection = firestore().collection('users');
84
85
// Add new document
86
const newUser = await usersCollection.add({
87
name: 'John Doe',
88
email: 'john@example.com',
89
createdAt: firestore.FieldValue.serverTimestamp()
90
});
91
92
// Get document reference
93
const userDoc = usersCollection.doc('userId');
94
95
// Collection group query across all 'messages' subcollections
96
const allMessages = firestore().collectionGroup('messages');
97
```
98
99
### Document References
100
101
Access and manipulate individual documents within collections.
102
103
```typescript { .api }
104
/**
105
* Get a reference to a document
106
* @param documentPath - Path to the document
107
* @returns DocumentReference instance
108
*/
109
doc(documentPath: string): FirebaseFirestoreTypes.DocumentReference;
110
111
interface DocumentReference<T = FirebaseFirestoreTypes.DocumentData> {
112
readonly firestore: FirebaseFirestoreTypes.Module;
113
readonly id: string;
114
readonly parent: FirebaseFirestoreTypes.CollectionReference<T>;
115
readonly path: string;
116
117
/**
118
* Get a subcollection reference
119
* @param collectionPath - Path to the subcollection
120
* @returns CollectionReference for the subcollection
121
*/
122
collection(collectionPath: string): FirebaseFirestoreTypes.CollectionReference;
123
124
/**
125
* Delete the document
126
* @returns Promise resolving when deletion completes
127
*/
128
delete(): Promise<void>;
129
130
/**
131
* Get the document data
132
* @param options - Optional get options
133
* @returns Promise resolving to document snapshot
134
*/
135
get(options?: FirebaseFirestoreTypes.GetOptions): Promise<FirebaseFirestoreTypes.DocumentSnapshot<T>>;
136
137
/**
138
* Set the document data (overwrites existing data)
139
* @param data - Document data to set
140
* @param options - Optional set options for merging
141
* @returns Promise resolving when set completes
142
*/
143
set(data: T, options?: FirebaseFirestoreTypes.SetOptions): Promise<void>;
144
145
/**
146
* Update specific fields in the document
147
* @param data - Partial data to update
148
* @returns Promise resolving when update completes
149
*/
150
update(data: Partial<T>): Promise<void>;
151
152
/**
153
* Update specific fields using field paths
154
* @param field - Field path to update
155
* @param value - New field value
156
* @param moreFieldsAndValues - Additional field-value pairs
157
* @returns Promise resolving when update completes
158
*/
159
update(field: keyof T | FirebaseFirestoreTypes.FieldPath, value: any, ...moreFieldsAndValues: any[]): Promise<void>;
160
161
/**
162
* Check if two document references are equal
163
* @param other - Other document reference to compare
164
* @returns True if references are equal
165
*/
166
isEqual(other: FirebaseFirestoreTypes.DocumentReference): boolean;
167
}
168
```
169
170
**Usage Examples:**
171
172
```typescript
173
import firestore from '@react-native-firebase/firestore';
174
175
// Get document reference
176
const userDoc = firestore().collection('users').doc('userId');
177
178
// Alternative: direct document path
179
const userDoc2 = firestore().doc('users/userId');
180
181
// Get document data
182
const snapshot = await userDoc.get();
183
if (snapshot.exists) {
184
console.log('User data:', snapshot.data());
185
}
186
187
// Set document data (overwrites)
188
await userDoc.set({
189
name: 'John Doe',
190
email: 'john@example.com',
191
updatedAt: firestore.FieldValue.serverTimestamp()
192
});
193
194
// Update specific fields
195
await userDoc.update({
196
lastLoginAt: firestore.FieldValue.serverTimestamp(),
197
loginCount: firestore.FieldValue.increment(1)
198
});
199
200
// Update using field paths
201
await userDoc.update('profile.displayName', 'John D.');
202
203
// Delete document
204
await userDoc.delete();
205
206
// Access subcollection
207
const postsCollection = userDoc.collection('posts');
208
```
209
210
### Document Snapshots
211
212
Read document data and metadata from snapshots.
213
214
```typescript { .api }
215
interface DocumentSnapshot<T = FirebaseFirestoreTypes.DocumentData> {
216
/**
217
* Get the document data
218
* @param options - Optional snapshot options
219
* @returns Document data or undefined if document doesn't exist
220
*/
221
data(options?: FirebaseFirestoreTypes.SnapshotOptions): T | undefined;
222
223
/**
224
* Get a specific field value
225
* @param fieldPath - Field path to retrieve
226
* @param options - Optional snapshot options
227
* @returns Field value
228
*/
229
get(fieldPath: keyof T | FirebaseFirestoreTypes.FieldPath, options?: FirebaseFirestoreTypes.SnapshotOptions): any;
230
231
readonly exists: boolean;
232
readonly id: string;
233
readonly metadata: FirebaseFirestoreTypes.SnapshotMetadata;
234
readonly ref: FirebaseFirestoreTypes.DocumentReference<T>;
235
}
236
237
interface SnapshotOptions {
238
serverTimestamps?: 'estimate' | 'previous' | 'none';
239
}
240
```
241
242
**Usage Examples:**
243
244
```typescript
245
import firestore from '@react-native-firebase/firestore';
246
247
const userDoc = firestore().collection('users').doc('userId');
248
const snapshot = await userDoc.get();
249
250
// Check if document exists
251
if (snapshot.exists) {
252
// Get all data
253
const userData = snapshot.data();
254
console.log('User:', userData);
255
256
// Get specific field
257
const email = snapshot.get('email');
258
console.log('Email:', email);
259
260
// Get nested field using FieldPath
261
const displayName = snapshot.get(new firestore.FieldPath('profile', 'displayName'));
262
263
// Check metadata
264
console.log('From cache:', snapshot.metadata.fromCache);
265
console.log('Has pending writes:', snapshot.metadata.hasPendingWrites);
266
}
267
```
268
269
## Types
270
271
```typescript { .api }
272
interface GetOptions {
273
/**
274
* Source for the get operation
275
* - 'default': Try cache first, then server
276
* - 'server': Always get from server
277
* - 'cache': Only get from cache
278
*/
279
source: 'default' | 'server' | 'cache';
280
}
281
282
interface SetOptions {
283
/**
284
* Whether to merge data with existing document
285
*/
286
merge?: boolean;
287
288
/**
289
* Specific fields to merge (requires merge: true)
290
*/
291
mergeFields?: (string | FirebaseFirestoreTypes.FieldPath)[];
292
}
293
294
interface SnapshotMetadata {
295
/**
296
* True if data came from local cache
297
*/
298
readonly fromCache: boolean;
299
300
/**
301
* True if document has local modifications not yet written to server
302
*/
303
readonly hasPendingWrites: boolean;
304
305
/**
306
* Check if metadata objects are equal
307
*/
308
isEqual(other: FirebaseFirestoreTypes.SnapshotMetadata): boolean;
309
}
310
```