-
Notifications
You must be signed in to change notification settings - Fork 131
/
index.js
1196 lines (998 loc) · 30.2 KB
/
index.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
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const debug = require('debug')('firestore-snippets-node');
// [START firestore_deps]
const admin = require('firebase-admin');
// [END firestore_deps]
// We supress these logs when not in NODE_ENV=debug for cleaner Mocha output
let console = {log: debug};
function initializeApp() {
process.env.GCLOUD_PROJECT = 'firestorebeta1test2';
// [START initialize_app]
admin.initializeApp({
credential: admin.credential.applicationDefault()
});
const db = admin.firestore();
// [START_EXCLUDE]
const settings = {timestampsInSnapshots: true};
db.settings(settings);
// [END_EXCLUDE]
// [END initialize_app]
return db;
}
function initializeAppFunctions() {
process.env.GCLOUD_PROJECT = 'firestorebeta1test2';
// [START initialize_app_functions]
const functions = require('firebase-functions');
admin.initializeApp(functions.config().firebase);
let db = admin.firestore();
// [END initialize_app_functions]
return db;
}
function initializeAppSA() {
// [START initialize_app_service_account]
let serviceAccount = require('path/to/serviceAccountKey.json');
admin.initializeApp({
credential: admin.credential.cert(serviceAccount)
});
let db = admin.firestore();
// [END initialize_app_service_account]
return db;
}
function demoInitialize(db) {
// [START demo_initialize]
// Fetch data from Firestore
db.collection('cities').get()
.then(documentSet => {
// Print the ID and contents of each document
documentSet.forEach(doc => {
console.log(doc.id, ' => ', doc.data());
});
})
.catch(err => {
// Error fetching documents
console.log('Error', err);
});
// [END demo_initialize]
}
// ============================================================================
// https://firebase.google.com/docs/firestore/quickstart
// ============================================================================
function quickstartAddData(db) {
// [START add_lovelace]
let docRef = db.collection('users').doc('alovelace');
let setAda = docRef.set({
first: 'Ada',
last: 'Lovelace',
born: 1815
});
// [END add_lovelace]
// [START add_turing]
let aTuringRef = db.collection('users').doc('aturing');
let setAlan = aTuringRef.set({
'first': 'Alan',
'middle': 'Mathison',
'last': 'Turing',
'born': 1912
});
// [END add_turing]
return Promise.all([setAda, setAlan]);
}
function quickstartQuery(db) {
// [START quickstart_query]
// Realtime listens are not yet supported in the Node.js SDK
let query = db.collection('users').where('born', '<', 1900)
.get()
.then(snapshot => {
snapshot.forEach(doc => {
console.log(doc.id, '=>', doc.data());
});
})
.catch(err => {
console.log('Error getting documents', err);
});
// [END quickstart_query]
return query;
}
function quickstartListen(db) {
// [START quickstart_listen]
db.collection('users').get()
.then((snapshot) => {
snapshot.forEach((doc) => {
console.log(doc.id, '=>', doc.data());
});
})
.catch((err) => {
console.log('Error getting documents', err);
});
// [END quickstart_listen]
}
// ============================================================================
// https://firebase.google.com/docs/firestore/data-model
// ============================================================================
function basicReferences(db) {
// [START doc_ref]
let alovelaceDocumentRef = db.collection('users').doc('alovelace');
// [END doc_ref]
// [START collection_ref]
let usersCollectionRef = db.collection('users');
// [END collection_ref]
}
function advancedReferences(db) {
// [START doc_ref_alternate]
let alovelaceDocumentRef = db.doc('users/alovelace');
// [END doc_ref_alternate]
// [START subcollection_ref]
let messageRef = db.collection('rooms').doc('roomA')
.collection('messages').doc('message1');
// [END subcollection_ref]
}
// ============================================================================
// https://firebase.google.com/docs/firestore/server/save-data
// ============================================================================
function setDocument(db) {
// [START set_document]
let data = {
name: 'Los Angeles',
state: 'CA',
country: 'USA'
};
// Add a new document in collection "cities" with ID 'LA'
let setDoc = db.collection('cities').doc('LA').set(data);
// [END set_document]
return setDoc.then(res => {
console.log('Set: ', res);
});
}
function dataTypes(db) {
// [START data_types]
let data = {
stringExample: 'Hello, World!',
booleanExample: true,
numberExample: 3.14159265,
dateExample: admin.firestore.Timestamp.fromDate(new Date('December 10, 1815')),
arrayExample: [5, true, 'hello'],
nullExample: null,
objectExample: {
a: 5,
b: true
}
};
let setDoc = db.collection('data').doc('one').set(data);
// [END data_types]
return setDoc.then(res => {
console.log('Set: ', res);
});
}
function addDocument(db) {
// [START add_document]
// Add a new document with a generated id.
let addDoc = db.collection('cities').add({
name: 'Tokyo',
country: 'Japan'
}).then(ref => {
console.log('Added document with ID: ', ref.id);
});
// [END add_document]
return addDoc.then(res => {
console.log('Add: ', res);
});
}
function addDocumentWithId(db) {
let data = {foo: 'bar '};
// [START add_document_id]
db.collection('cities').doc('new-city-id').set(data);
// [END add_document_id]
}
function addLater(db) {
// [START add_later]
let newCityRef = db.collection('cities').doc();
// Later...
let setDoc = newCityRef.set({
// ...
});
// [END add_later]
return setDoc.then(res => {
console.log('Add: ', res);
});
}
function updateDocument(db) {
// [START update_document]
let cityRef = db.collection('cities').doc('DC');
// Set the 'capital' field of the city
let updateSingle = cityRef.update({capital: true});
// [END update_document]
return Promise.all([updateSingle]).then(res => {
console.log('Update: ', res);
});
}
function updateDocumentArray(db) {
// [START update_document_array]
let admin = require('firebase-admin');
// ...
let washingtonRef = db.collection('cities').doc('DC');
// Atomically add a new region to the "regions" array field.
let arrUnion = washingtonRef.update({
regions: admin.firestore.FieldValue.arrayUnion('greater_virginia')
});
// Atomically remove a region from the "regions" array field.
let arrRm = washingtonRef.update({
regions: admin.firestore.FieldValue.arrayRemove('east_coast')
});
// [END update_document_array]
return Promise.all([arrUnion, arrRm]).then(res => {
console.log('Update array: ', res);
});
}
function updateDocumentIncrement(db) {
// [START update_document_increment]
let admin = require('firebase-admin');
// ...
let washingtonRef = db.collection('cities').doc('DC');
// Atomically increment the population of the city by 50.
let popIncrement = washingtonRef.update({
population: admin.firestore.FieldValue.increment(50)
});
// [END update_document_increment]
return popIncrement.then(res => {
console.log('Increment: ' + res);
});
}
function updateDocumentMany(db) {
// [START update_document_many]
let cityRef = db.collection('cities').doc('DC');
let updateMany = cityRef.update({
name: 'Washington D.C.',
country: 'USA',
capital: true
});
// [END update_document_many]
return updateMany.then(res => {
console.log('Update: ', res);
});
}
function updateCreateIfMissing(db) {
// [START update_create_if_missing]
let cityRef = db.collection('cities').doc('BJ');
let setWithOptions = cityRef.set({
capital: true
}, {merge: true});
// [END update_create_if_missing]
return setWithOptions.then(res => {
console.log('Update: ', res);
});
}
function updateServerTimestamp(db) {
// Create the object before updating it (racy on first run, oh well)
db.collection('objects').doc('some-id').set({});
// [START update_with_server_timestamp]
// Get the `FieldValue` object
let FieldValue = require('firebase-admin').firestore.FieldValue;
// Create a document reference
let docRef = db.collection('objects').doc('some-id');
// Update the timestamp field with the value from the server
let updateTimestamp = docRef.update({
timestamp: FieldValue.serverTimestamp()
});
// [END update_with_server_timestamp]
return updateTimestamp.then(res => {
console.log('Update: ', res);
});
}
function updateDeleteField(db) {
// [START update_delete_field]
// Get the `FieldValue` object
let FieldValue = require('firebase-admin').firestore.FieldValue;
// Create a document reference
let cityRef = db.collection('cities').doc('BJ');
// Remove the 'capital' field from the document
let removeCapital = cityRef.update({
capital: FieldValue.delete()
});
// [END update_delete_field]
return removeCapital.then(res => {
console.log('Update: ', res);
});
}
function updateNested(db) {
// [START update_nested]
let initialData = {
name: 'Frank',
age: 12,
favorites: {
food: 'Pizza',
color: 'Blue',
subject: 'recess'
}
};
// [START_EXCLUDE]
db.collection('users').doc('Frank').set(initialData);
// [END_EXCLUDE]
let updateNested = db.collection('users').doc('Frank').update({
age: 13,
'favorites.color': 'Red'
});
// [END update_nested]
return updateNested.then(res => {
console.log('Update: ', res);
});
}
function deleteDocument(db) {
// [START delete_document]
let deleteDoc = db.collection('cities').doc('DC').delete();
// [END delete_document]
return deleteDoc.then(res => {
console.log('Delete: ', res);
});
}
function transaction(db) {
// [START transaction]
// Initialize document
let cityRef = db.collection('cities').doc('SF');
let setCity = cityRef.set({
name: 'San Francisco',
state: 'CA',
country: 'USA',
capital: false,
population: 860000
});
let transaction = db.runTransaction(t => {
return t.get(cityRef)
.then(doc => {
// Add one person to the city population.
// Note: this could be done without a transaction
// by updating the population using FieldValue.increment()
let newPopulation = doc.data().population + 1;
t.update(cityRef, {population: newPopulation});
});
}).then(result => {
console.log('Transaction success!');
}).catch(err => {
console.log('Transaction failure:', err);
});
// [END transaction]
return transaction;
}
function transactionWithResult(db) {
// [START transaction_with_result]
let cityRef = db.collection('cities').doc('SF');
let transaction = db.runTransaction(t => {
return t.get(cityRef)
.then(doc => {
let newPopulation = doc.data().population + 1;
if (newPopulation <= 1000000) {
t.update(cityRef, {population: newPopulation});
return Promise.resolve('Population increased to ' + newPopulation);
} else {
return Promise.reject('Sorry! Population is too big.');
}
});
}).then(result => {
console.log('Transaction success', result);
}).catch(err => {
console.log('Transaction failure:', err);
});
// [END transaction_with_result]
return transaction;
}
function updateBatch(db) {
// [START update_data_batch]
// Get a new write batch
let batch = db.batch();
// Set the value of 'NYC'
let nycRef = db.collection('cities').doc('NYC');
batch.set(nycRef, {name: 'New York City'});
// Update the population of 'SF'
let sfRef = db.collection('cities').doc('SF');
batch.update(sfRef, {population: 1000000});
// Delete the city 'LA'
let laRef = db.collection('cities').doc('LA');
batch.delete(laRef);
// Commit the batch
return batch.commit().then(function () {
// [START_EXCLUDE]
console.log('Batched.');
// [END_EXCLUDE]
});
// [END update_data_batch]
}
// ============================================================================
// https://firebase.google.com/docs/firestore/server/retrieve-data
// ============================================================================
function exampleData(db) {
// [START example_data]
let citiesRef = db.collection('cities');
let setSf = citiesRef.doc('SF').set({
name: 'San Francisco', state: 'CA', country: 'USA',
capital: false, population: 860000,
regions: ['west_coast', 'norcal']
});
let setLa = citiesRef.doc('LA').set({
name: 'Los Angeles', state: 'CA', country: 'USA',
capital: false, population: 3900000,
regions: ['west_coast', 'socal']
});
let setDc = citiesRef.doc('DC').set({
name: 'Washington, D.C.', state: null, country: 'USA',
capital: true, population: 680000,
regions: ['east_coast']
});
let setTok = citiesRef.doc('TOK').set({
name: 'Tokyo', state: null, country: 'Japan',
capital: true, population: 9000000,
regions: ['kanto', 'honshu']
});
let setBj = citiesRef.doc('BJ').set({
name: 'Beijing', state: null, country: 'China',
capital: true, population: 21500000,
regions: ['jingjinji', 'hebei']
});
// [END example_data]
return Promise.all([setSf, setLa, setDc, setTok, setBj]);
}
function exampleDataTwo(db) {
// [START example_data_two]
const citiesRef = db.collection('cities');
let setSf = citiesRef.doc('SF').set({
name: 'San Francisco', state: 'CA', country: 'USA',
capital: false, population: 860000
});
let setLa = citiesRef.doc('LA').set({
name: 'Los Angeles', state: 'CA', country: 'USA',
capital: false, population: 3900000
});
let setDc = citiesRef.doc('DC').set({
name: 'Washington, D.C.', state: null, country: 'USA',
capital: true, population: 680000
});
let setTok = citiesRef.doc('TOK').set({
name: 'Tokyo', state: null, country: 'Japan',
capital: true, population: 9000000
});
let setBj = citiesRef.doc('BJ').set({
name: 'Beijing', state: null, country: 'China',
capital: true, population: 21500000
});
// [END example_data_two]
return Promise.all([setSf, setLa, setDc, setTok, setBj]);
}
function getDocument(db) {
// [START get_document]
let cityRef = db.collection('cities').doc('SF');
let getDoc = cityRef.get()
.then(doc => {
if (!doc.exists) {
console.log('No such document!');
} else {
console.log('Document data:', doc.data());
}
})
.catch(err => {
console.log('Error getting document', err);
});
// [END get_document]
return getDoc;
}
function getDocumentEmpty(db) {
let cityRef = db.collection('cities').doc('Amexico');
let getDoc = cityRef.get()
.then(doc => {
if (!doc.exists) {
console.log('No such document!');
} else {
console.log('Document data:', doc.data());
}
});
return getDoc;
}
function getMultiple(db) {
// [START get_multiple]
let citiesRef = db.collection('cities');
let query = citiesRef.where('capital', '==', true).get()
.then(snapshot => {
if (snapshot.empty) {
console.log('No matching documents.');
return;
}
snapshot.forEach(doc => {
console.log(doc.id, '=>', doc.data());
});
})
.catch(err => {
console.log('Error getting documents', err);
});
// [END get_multiple]
return query;
}
function getAll(db) {
// [START get_all]
let citiesRef = db.collection('cities');
let allCities = citiesRef.get()
.then(snapshot => {
snapshot.forEach(doc => {
console.log(doc.id, '=>', doc.data());
});
})
.catch(err => {
console.log('Error getting documents', err);
});
// [END get_all]
return allCities;
}
function getCollections(db) {
// [START get_collections]
let sfRef = db.collection('cities').doc('SF');
sfRef.getCollections().then(collections => {
collections.forEach(collection => {
console.log('Found subcollection with id:', collection.id);
});
});
// [END get_collections]
}
// ============================================================================
// https://firebase.google.com/docs/firestore/server/query-data
// ============================================================================
function simpleQuery(db) {
// [START simple_query]
// Create a reference to the cities collection
let citiesRef = db.collection('cities');
// Create a query against the collection
let queryRef = citiesRef.where('state', '==', 'CA');
// [END simple_query]
return queryRef.get()
.then(res => {
res.forEach(doc => {
console.log(doc.id, ' => ', doc.data());
});
});
}
function queryAndFilter(db) {
// [START create_query]
// Create a reference to the cities collection
let citiesRef = db.collection('cities');
// Create a query against the collection
let queryRef = citiesRef.where('capital', '==', true);
// [END create_query]
// [START example_filters]
let stateQuery = citiesRef.where('state', '==', 'CA');
let populationQuery = citiesRef.where('population', '<', 1000000);
let nameQuery = citiesRef.where('name', '>=', 'San Francisco');
// [END example_filters]
return Promise.all([stateQuery.get(), populationQuery.get(), nameQuery.get()])
.then(res => {
res.forEach(r => {
r.forEach(d => {
console.log('Get:', d);
});
console.log();
});
});
}
function arrayFilter(db) {
let citiesRef = db.collection('cities');
// [START array_contains_filter]
let westCoastCities = citiesRef.where('regions', 'array-contains',
'west_coast');
// [END array_contains_filter]
return westCoastCities.get()
.then(res => {
console.log('West Coast get: ', res);
});
}
function orderAndLimit(db) {
let citiesRef = db.collection('cities');
// [START order_limit]
let firstThree = citiesRef.orderBy('name').limit(3);
// [END order_limit]
// [START order_limit_desc]
let lastThree = citiesRef.orderBy('name', 'desc').limit(3);
// [END order_limit_desc]
// [START order_multi_field]
let byStateByPop = citiesRef.orderBy('state').orderBy('population', 'desc');
// [END order_multi_field]
// [START where_and_order]
let biggest = citiesRef.where('population', '>', 2500000)
.orderBy('population').limit(2);
// [END where_and_order]
return Promise.all([firstThree.get(), lastThree.get(), biggest.get()])
.then(res => {
res.forEach(r => {
r.forEach(d => {
console.log('Get:', d);
});
console.log();
});
});
}
function validInvalidQueries(db) {
let citiesRef = db.collection('cities');
// [START valid_chained]
citiesRef.where('state', '==', 'CO').where('name', '==', 'Denver');
// [END valid_chained]
// [START invalid_chained]
citiesRef.where('state', '==', 'CA').where('population', '<', 1000000);
// [END invalid_chained]
// [START valid_range]
citiesRef.where('state', '>=', 'CA').where('state', '<=', 'IN');
citiesRef.where('state', '==', 'CA').where('population', '>', 1000000);
// [END valid_range]
// [START invalid_range]
citiesRef.where('state', '>=', 'CA').where('population', '>', 1000000);
// [END invalid_range]
// [START valid_order_by]
citiesRef.where('population', '>', 2500000).orderBy('population');
// [END valid_order_by]
// [START invalid_order_by]
citiesRef.where('population', '>', 2500000).orderBy('country');
// [END invalid_order_by]
}
function streamSnapshot(db, done) {
// [START query_realtime]
let query = db.collection('cities').where('state', '==', 'CA');
let observer = query.onSnapshot(querySnapshot => {
console.log(`Received query snapshot of size ${querySnapshot.size}`);
// [START_EXCLUDE]
observer();
done();
// [END_EXCLUDE]
}, err => {
console.log(`Encountered error: ${err}`);
});
// [END query_realtime]
}
function listenDiffs(db, done) {
// [START listen_diffs]
let observer = db.collection('cities').where('state', '==', 'CA')
.onSnapshot(querySnapshot => {
querySnapshot.docChanges().forEach(change => {
if (change.type === 'added') {
console.log('New city: ', change.doc.data());
}
if (change.type === 'modified') {
console.log('Modified city: ', change.doc.data());
}
if (change.type === 'removed') {
console.log('Removed city: ', change.doc.data());
}
});
// [START_EXCLUDE silent]
observer();
done();
// [END_EXCLUDE]
});
// [END listen_diffs]
}
function streamDocument(db, done) {
// [START doc_realtime]
let doc = db.collection('cities').doc('SF');
let observer = doc.onSnapshot(docSnapshot => {
console.log(`Received doc snapshot: ${docSnapshot}`);
// [START_EXCLUDE]
observer();
done();
// [END_EXCLUDE]
}, err => {
console.log(`Encountered error: ${err}`);
});
// [END doc_realtime]
}
function detatchListener(db) {
// [START detach_listener]
let unsub = db.collection('cities').onSnapshot(() => {
});
// ...
// Stop listening for changes
unsub();
// [END detach_listener]
}
function listenErrors(db) {
// [START listen_errors]
db.collection('cities')
.onSnapshot((snapshot) => {
//...
}, (error) => {
//...
});
// [END listen_errors]
}
function collectionGroupQuery(db) {
// [START fs_collection_group_query_data_setup]
let citiesRef = db.collection('cities');
let landmarks = Promise.all([
citiesRef.doc('SF').collection('landmarks').doc().set({
name: 'Golden Gate Bridge',
type: 'bridge'
}),
citiesRef.doc('SF').collection('landmarks').doc().set({
name: 'Legion of Honor',
type: 'museum'
}),
citiesRef.doc('LA').collection('landmarks').doc().set({
name: 'Griffith Park',
type: 'park'
}),
citiesRef.doc('LA').collection('landmarks').doc().set({
name: 'The Getty',
type: 'museum'
}),
citiesRef.doc('DC').collection('landmarks').doc().set({
name: 'Lincoln Memorial',
type: 'memorial'
}),
citiesRef.doc('DC').collection('landmarks').doc().set({
name: 'National Air and Space Museum',
type: 'museum'
}),
citiesRef.doc('TOK').collection('landmarks').doc().set({
name: 'Ueno Park',
type: 'park'
}),
citiesRef.doc('TOK').collection('landmarks').doc().set({
name: 'National Museum of Nature and Science',
type: 'museum'
}),
citiesRef.doc('BJ').collection('landmarks').doc().set({
name: 'Jingshan Park',
type: 'park'
}),
citiesRef.doc('BJ').collection('landmarks').doc().set({
name: 'Beijing Ancient Observatory',
type: 'museum'
})
]);
// [END fs_collection_group_query_data_setup]
landmarks.then((l) => console.log(l));
// [START fs_collection_group_query]
let museums = db.collectionGroup('landmarks').where('type', '==', 'museum');
museums.get().then(function(querySnapshot) {
querySnapshot.forEach(function(doc) {
console.log(doc.id, ' => ', doc.data());
});
});
// [END fs_collection_group_query]
}
// ============================================================================
// https://firebase.google.com/docs/firestore/query-data/query-cursors
// ============================================================================
function simpleCursors(db) {
// [START cursor_simple_start_at]
let startAt = db.collection('cities')
.orderBy('population')
.startAt(1000000);
// [END cursor_simple_start_at]
// [START cursor_simple_end_at]
let endAt = db.collection('cities')
.orderBy('population')
.endAt(1000000);
// [END cursor_simple_end_at]
return Promise.all([
startAt.limit(10).get(),
endAt.limit(10).get()
]);
}
function snapshotCursors(db) {
// [START fs_start_at_snapshot_query_cursor]
let docRef = db.collection('cities').doc('SF');
return docRef.get().then(snapshot => {
let startAtSnapshot = db.collection('cities')
.orderBy('population')
.startAt(snapshot);
return startAtSnapshot.limit(10).get();
});
// [END fs_start_at_snapshot_query_cursor]
}
function paginateQuery(db) {
// [START cursor_paginate]
let first = db.collection('cities')
.orderBy('population')
.limit(3);
let paginate = first.get()
.then((snapshot) => {
// ...
// Get the last document
let last = snapshot.docs[snapshot.docs.length - 1];
// Construct a new query starting at this document.
// Note: this will not have the desired effect if multiple
// cities have the exact same population value.
let next = db.collection('cities')
.orderBy('population')
.startAfter(last.data().population)
.limit(3);
// Use the query for pagination
// [START_EXCLUDE]
return next.get().then((snapshot) => {
console.log('Num results:', snapshot.docs.length);
});
// [END_EXCLUDE]
});
// [END cursor_paginate]
return paginate;
}
function multipleCursorConditions(db) {
// [START cursor_multiple_one_start]
// Will return all Springfields
let startAtName = db.collection('cities')
.orderBy('name')
.orderBy('state')
.startAt('Springfield');
// [END cursor_multiple_one_start]
// [START cursor_multiple_two_start]
// Will return 'Springfield, Missouri' and 'Springfield, Wisconsin'
let startAtNameAndState = db.collection('cities')
.orderBy('name')
.orderBy('state')
.startAt('Springfield', 'Missouri');
// [END cursor_multiple_two_start]
return Promise.all([
startAtName.get(),
startAtNameAndState.get()
]);
}
// [START delete_collection]
function deleteCollection(db, collectionPath, batchSize) {
let collectionRef = db.collection(collectionPath);
let query = collectionRef.orderBy('__name__').limit(batchSize);
return new Promise((resolve, reject) => {
deleteQueryBatch(db, query, batchSize, resolve, reject);
});
}
function deleteQueryBatch(db, query, batchSize, resolve, reject) {
query.get()
.then((snapshot) => {
// When there are no documents left, we are done
if (snapshot.size == 0) {
return 0;
}
// Delete documents in a batch
let batch = db.batch();
snapshot.docs.forEach((doc) => {
batch.delete(doc.ref);