-
Notifications
You must be signed in to change notification settings - Fork 1
/
firestore.js
416 lines (360 loc) · 10.9 KB
/
firestore.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
/*===================================================================//
VERSION 8 (current)
//===================================================================*/
import firebase, { firestore } from "./init-firebase";
// Collection/doc ref
const collectionRef = firestore.collection("some-collection");
const documentRef = firestore.doc("some-collection/some-doc-name");
// Firestore field values
const fieldVal = firebase.firestore.FieldValue;
// Add a document to a collection | Option #1
const addDocOption1 = async () => {
await collectionRef.doc("some-doc-name").set({
contents: "some-data",
});
};
// Add a document to a collection | Option #2
const addDocOption2 = async () => {
await documentRef.set({
contents: "some-data",
});
};
// Add a document to a collection (with an auto assigned doc ID) | Option #1
const addDocWithAutoIdOption1 = async () => {
await collectionRef.add({
contents: "some-data",
});
};
// Add a document to a collection (with an auto assigned doc ID) | Option #2
const addDocWithAutoIdOption2 = async () => {
await collectionRef.set({
contents: "some-data",
});
};
// Merging a document if it exists
const mergeExisitngDoc = async () => {
await documentRef.set(
{
contents: "some-data",
},
{ merge: true }
);
};
// Deleting a document
const deleteDoc = async () => {
await documentRef.delete();
};
// Using a server timestamp
const timestamp = fieldVal.serverTimestamp();
const useTimestamp = async () => {
await documentRef.set({
createdAt: timestamp,
});
};
// Add/update elements in an array
const arrayAdd = fieldVal.arrayUnion();
const updateAnArray = async () => {
await documentRef.update({
recentUpdates: arrayAdd("8/17/2021"),
});
};
// Remove elements in an array
const arrayRemove = fieldVal.arrayRemove();
const RemoveArrayItem = async () => {
await documentRef.update({
recentUpdates: arrayRemove("7/04/2021"),
});
};
// Increment/decrement a numeric value/counter
const increment = fieldVal.increment();
const incrementCounter = async () => {
await documentRef.update({
increasingValue: increment(33),
decreasingValue: increment(-13),
});
};
// Get a new batch
const batch = firestore.batch();
// Set a batch value
batch.set(documentRef, { contents: "some-data" });
// Batch update
batch.update(documentRef, { contents: "some-updated-data" });
// Batch delete
batch.delete(documentRef);
// Commit the batch
const commitBatch = async () => {
await batch.commit().then(() => {
// Batch actions successful
});
};
// Get/read a document once
const getDocData = async (docRef) => {
await docRef.get().then((doc) => {
if (doc.exists) {
console.log("Document data:", doc.data());
}
});
};
// Get/read documents in a collection once
const getCollectionDocs = async (collectionRef) => {
await collectionRef.get().then((querySnapshot) => {
querySnapshot.forEach((doc) => {
const data = doc.data();
console.log(data);
});
});
};
// Listen for document changes
const docListener = (docRef) => {
docRef.onSnapshot((doc) => {
const data = doc.data();
console.log(data);
});
};
const unsubscribe = docListener(); // Detach listener
unsubscribe(); // Destroy
// Listen for collection changes
const collectionListener = (collectionRef) => {
collectionRef.onSnapshot((querySnapshot) => {
let dataArray = [];
querySnapshot.forEach((doc) => {
dataArray.push(doc.data());
});
dataArray.map((d) => console.log(d));
});
};
const unsubscribe = collectionListener(); // Detach listener
unsubscribe(); // Destroy
// Queries
const collectionRef = firestore.collection("some-collection");
const someQuery = collectionRef.where("some-data", "==", "awesome");
const compoundQuery = collectionRef.where("some-value", ">=", 1).where("some-value", "<=", 10);
const arrayQuery = collectionRef.where("some-values", "array-contains", "some-array-value");
const collectionGroupQuery = collectionRef
.collectionGroup("some-data")
.where("type", "==", "super-awesome");
const orderQuery = collectionRef.orderBy("createdAt", "desc".limit(100));
const filterAndOrderQuery = collectionRef.where("some-value", ">", 5).orderBy("some-value");
// Use a query to get collection docs
const getCollectionDocs = async (collectionRef) => {
const collectionRef = firestore.collection(collection);
const collectionQuery = collectionRef.where("some-data", "==", true);
await collectionQuery.get().then((querySnapshot) => {
querySnapshot.forEach((doc) => {
const data = doc.data();
console.log(data);
});
});
};
// Use a query with collection listener
const collectionListener = (collectionRef) => {
const collectionRef = firestore.collection(collection);
const collectionQuery = collectionRef.where("some-data", "==", true);
collectionQuery.onSnapshot((querySnapshot) => {
let dataArray = [];
querySnapshot.forEach((doc) => {
dataArray.push(doc.data());
});
dataArray.map((d) => console.log(d));
});
};
// Paginate a query
const first = collectionRef.orderBy("createdAt").limit(25);
return first.get().then((docSnaps) => {
const lastVisible = docSnaps.docs[docSnaps.docs.length - 1];
console.log("last", lastVisible);
const next = collectionRef.orderBy("createdAt").startAfter(lastVisible).limit(25);
});
/*===================================================================//
VERSION 9 (beta)
//===================================================================*/
import { firestore } from "./init-firebase";
import {
doc,
addDoc,
setDoc,
getDoc,
updateDoc,
collection,
deleteDoc,
serverTimestamp,
arrayUnion,
arrayRemove,
increment,
writeBatch,
query,
where,
getDocs,
onSnapshot,
orderBy,
limit,
startAt,
endAt,
startAfter,
} from "firebase/firestore";
// Collection/doc ref
const collectionRef = collection(firestore, "some-collection");
const documentRef = doc(firestore, "some-collection", "some-doc-name");
// Add a document to a collection | Option #1
const addDocOption1 = async () => {
await setDoc(collectionRef, "some-doc-name", {
contents: "some-data",
});
};
// Add a document to a collection | Option #2
const addDocOption2 = async () => {
await setDoc(documentRef, {
contents: "some-data",
});
};
// Add a document to a collection (with an auto assigned doc ID) | Option #1
const addDocWithAutoIdOption1 = async () => {
await addDoc(collectionRef, {
contents: "some-data",
});
};
// Add a document to a collection (with an auto assigned doc ID) | Option #2
const addDocWithAutoIdOption2 = async () => {
await setDoc(collectionRef, {
contents: "some-data",
});
};
// Merging a document if it exists
const mergeExisitngDoc = async () => {
await setDoc(
documentRef,
{
contents: "some-data",
},
{ merge: true }
);
};
// Deleting a document
const deleteDoc = async () => {
await deleteDoc(documentRef);
};
// Using a server timestamp
const timestamp = serverTimestamp();
const useTimestamp = async () => {
await setDoc(collectionRef, {
createdAt: timestamp,
});
};
// Add/update elements in an array
const updateAnArray = async () => {
await updateDoc(documentRef, {
recentUpdates: arrayUnion("8/17/2021"),
});
};
// Remove elements in an array
const RemoveArrayItem = async () => {
await updateDoc(documentRef, {
recentUpdates: arrayRemove("7/04/2021"),
});
};
// Increment/decrement a numeric value/counter
const incrementCounter = async () => {
await updateDoc(documentRef, {
increasingValue: increment(33),
decreasingValue: increment(-13),
});
};
// Get a new batch
const batch = writeBatch(firestore);
// Set a batch value
batch.set(documentRef, { contents: "some-data" });
// Batch update
batch.update(documentRef, { contents: "some-updated-data" });
// Batch delete
batch.delete(documentRef);
// Commit the batch
const commitBatch = async () => {
await batch.commit().then(() => {
// Batch actions successful
});
};
// Get/read a document once
const getDocData = async (collection, docId) => {
const docRef = doc(firestore, collection, docId);
const docSnap = await getDoc(docRef);
if (docSnap.exists()) {
console.log("Document data:", doc.data());
}
};
// Get/read documents in a collection once
const getCollectionDocs = async (collection) => {
const collectionRef = collection(firestore, collection);
const querySnapshot = await getDocs(collectionRef);
querySnapshot.forEach((doc) => {
const data = doc.data();
console.log(data);
});
};
// Listen for document changes
const docListener = (collection, docId) => {
const docRef = doc(firestore, collection, docId);
onSnapshot(docRef, (doc) => {
const data = doc.data();
console.log(data);
});
};
const unsubscribe = docListener(); // Detach listener
unsubscribe(); // Destroy
// Listen for collection changes
const collectionListener = (collection) => {
const collectionRef = collection(firestore, collection);
onSnapshot(collectionRef, (querySnapshot) => {
let dataArray = [];
querySnapshot.forEach((doc) => {
dataArray.push(doc.data());
});
dataArray.map((d) => console.log(d));
});
};
const unsubscribe = collectionListener(); // Detach listener
unsubscribe(); // Destroy
// Queries
const collectionRef = collection(firestore, "some-collection");
const someQuery = query(collectionRef, where("some-data", "==", "awesome"));
const compoundQuery = query(
collectionRef,
where("some-value", ">=", 1),
where("some-value", "<=", 10)
);
const arrayQuery = query(collectionRef, where("some-values", "array-contains", "some-array-value"));
const orderQuery = query(collectionRef, orderBy("createdAt", "desc"), limit(100));
const filterAndOrderQuery = query(
collectionRef,
where("some-value", ">", 5),
orderBy("some-value")
);
const paginateStart = query(collectionRef, orderBy("createdAt"), startAt(25));
const paginateEnd = query(collectionRef, orderBy("createdAt"), endAt(50));
// Use a query to get collection docs
const getCollectionDocs = async (collection) => {
const collectionRef = collection(firestore, collection);
const collectionQuery = query(collectionRef, where("some-data", "==", true));
const querySnapshot = await getDocs(collectionQuery);
querySnapshot.forEach((doc) => {
const data = doc.data();
console.log(data);
});
};
// Use a query with collection listener
const collectionListener = (collection) => {
const collectionRef = collection(firestore, collection);
const collectionQuery = query(collectionRef, where("some-data", "==", true));
onSnapshot(collectionQuery, (querySnapshot) => {
let dataArray = [];
querySnapshot.forEach((doc) => {
dataArray.push(doc.data());
});
dataArray.map((d) => console.log(d));
});
};
// Paginate a query
const first = query(collectionRef, orderBy("createdAt"), limit(25));
const docSnaps = await getDocs(first);
const lastVisible = docSnaps.docs[docSnaps.docs.length - 1];
console.log("last", lastVisible);
const next = query(collectionRef, orderBy("createdAt"), startAfter(lastVisible), limit(25));