-
Notifications
You must be signed in to change notification settings - Fork 253
/
Copy pathtest.firestore.js
1144 lines (1013 loc) · 42.6 KB
/
test.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
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
import firebase from 'firebase/app';
import 'firebase/firestore';
const { expect } = require('chai');
// [START city_custom_object]
class City {
constructor (name, state, country ) {
this.name = name;
this.state = state;
this.country = country;
}
toString() {
return this.name + ', ' + this.state + ', ' + this.country;
}
}
// Firestore data converter
var cityConverter = {
toFirestore: function(city) {
return {
name: city.name,
state: city.state,
country: city.country
};
},
fromFirestore: function(snapshot, options){
const data = snapshot.data(options);
return new City(data.name, data.state, data.country);
}
};
// [END city_custom_object]
describe("firestore", () => {
var db;
before(() => {
var config = {
apiKey: "AIzaSyCM61mMr_iZnP1DzjT1PMB5vDGxfyWNM64",
authDomain: "firestore-snippets.firebaseapp.com",
projectId: "firestore-snippets"
};
var app = firebase.initializeApp(config);
db = firebase.firestore(app);
// firebase.firestore.setLogLevel("debug");
});
it("should be able to set the cache size", () => {
// [START fs_setup_cache]
firebase.firestore().settings({
cacheSizeBytes: firebase.firestore.CACHE_SIZE_UNLIMITED
});
// [END fs_setup_cache]
});
it("should be initializable with persistence", () => {
firebase.initializeApp({
apiKey: '### FIREBASE API KEY ###',
authDomain: '### FIREBASE AUTH DOMAIN ###',
projectId: '### FIREBASE PROJECT ID ###',
} ,"persisted_app");
// [START initialize_persistence]
firebase.firestore().enablePersistence()
.catch((err) => {
if (err.code == 'failed-precondition') {
// Multiple tabs open, persistence can only be enabled
// in one tab at a a time.
// ...
} else if (err.code == 'unimplemented') {
// The current browser does not support all of the
// features required to enable persistence
// ...
}
});
// Subsequent queries will use persistence, if it was enabled successfully
// [END initialize_persistence]
});
it("should be able to enable/disable network", () => {
var disable =
// [START disable_network]
firebase.firestore().disableNetwork()
.then(() => {
// Do offline actions
// [START_EXCLUDE]
console.log("Network disabled!");
// [END_EXCLUDE]
});
// [END disable_network]
var enable =
// [START enable_network]
firebase.firestore().enableNetwork()
.then(() => {
// Do online actions
// [START_EXCLUDE]
console.log("Network enabled!");
// [END_EXCLUDE]
});
// [END enable_network]
return Promise.all([enable, disable]);
});
it("should reply with .fromCache fields", () => {
// [START use_from_cache]
db.collection("cities").where("state", "==", "CA")
.onSnapshot({ includeMetadataChanges: true }, (snapshot) => {
snapshot.docChanges().forEach((change) => {
if (change.type === "added") {
console.log("New city: ", change.doc.data());
}
var source = snapshot.metadata.fromCache ? "local cache" : "server";
console.log("Data came from " + source);
});
});
// [END use_from_cache]
});
describe("collection('users')", () => {
it("should add data to a collection", () => {
var output =
// [START add_ada_lovelace]
db.collection("users").add({
first: "Ada",
last: "Lovelace",
born: 1815
})
.then((docRef) => {
console.log("Document written with ID: ", docRef.id);
})
.catch((error) => {
console.error("Error adding document: ", error);
});
// [END add_ada_lovelace]
return output;
});
it("should get all users", () => {
var output =
// [START get_all_users]
db.collection("users").get().then((querySnapshot) => {
querySnapshot.forEach((doc) => {
console.log(`${doc.id} => ${doc.data()}`);
});
});
// [END get_all_users]
return output;
});
it("should add data to a collection with new fields", () => {
var output =
// [START add_alan_turing]
// Add a second document with a generated ID.
db.collection("users").add({
first: "Alan",
middle: "Mathison",
last: "Turing",
born: 1912
})
.then((docRef) => {
console.log("Document written with ID: ", docRef.id);
})
.catch((error) => {
console.error("Error adding document: ", error);
});
// [END add_alan_turing]
return output;
});
it("should loop through a watched collection", (done) => {
// This is not a typo.
var unsubscribe =
// [START listen_for_users]
db.collection("users")
.where("born", "<", 1900)
.onSnapshot((snapshot) => {
console.log("Current users born before 1900:");
snapshot.forEach((userSnapshot) => {
console.log(userSnapshot.data());
});
});
// [END listen_for_users]
setTimeout(() => {
unsubscribe();
done();
}, 1500);
});
it("should reference a specific document", () => {
// [START doc_reference]
var alovelaceDocumentRef = db.collection('users').doc('alovelace');
// [END doc_reference]
});
it("should reference a specific collection", () => {
// [START collection_reference]
var usersCollectionRef = db.collection('users');
// [END collection_reference]
});
it("should reference a specific document (alternative)", () => {
// [START doc_reference_alternative]
var alovelaceDocumentRef = db.doc('users/alovelace');
// [END doc_reference_alternative]
});
it("should reference a document in a subcollection", () => {
// [START subcollection_reference]
var messageRef = db.collection('rooms').doc('roomA')
.collection('messages').doc('message1');
// [END subcollection_reference]
});
it("should set a document", () => {
var output =
// [START set_document]
// Add a new document in collection "cities"
db.collection("cities").doc("LA").set({
name: "Los Angeles",
state: "CA",
country: "USA"
})
.then(() => {
console.log("Document successfully written!");
})
.catch((error) => {
console.error("Error writing document: ", error);
});
// [END set_document]
return output;
});
it("should set document with a custom object converter", () => {
var output =
// [START set_custom_object]
// Set with cityConverter
db.collection("cities").doc("LA")
.withConverter(cityConverter)
.set(new City("Los Angeles", "CA", "USA"));
// [END set_custom_object]
return output;
});
it("should get document with a custom object converter", () => {
var output =
// [START get_custom_object]
db.collection("cities").doc("LA")
.withConverter(cityConverter)
.get().then((doc) => {
if (doc.exists){
// Convert to City object
var city = doc.data();
// Use a City instance method
console.log(city.toString());
} else {
console.log("No such document!");
}}).catch((error) => {
console.log("Error getting document:", error);
});
// [END get_custom_object]
return output;
});
it("should support batch writes", (done) => {
// [START write_batch]
// Get a new write batch
var batch = db.batch();
// Set the value of 'NYC'
var nycRef = db.collection("cities").doc("NYC");
batch.set(nycRef, {name: "New York City"});
// Update the population of 'SF'
var sfRef = db.collection("cities").doc("SF");
batch.update(sfRef, {"population": 1000000});
// Delete the city 'LA'
var laRef = db.collection("cities").doc("LA");
batch.delete(laRef);
// Commit the batch
batch.commit().then(() => {
// [START_EXCLUDE]
done();
// [END_EXCLUDE]
});
// [END write_batch]
});
it("should set a document with every datatype #UNVERIFIED", () => {
// [START data_types]
var docData = {
stringExample: "Hello world!",
booleanExample: true,
numberExample: 3.14159265,
dateExample: firebase.firestore.Timestamp.fromDate(new Date("December 10, 1815")),
arrayExample: [5, true, "hello"],
nullExample: null,
objectExample: {
a: 5,
b: {
nested: "foo"
}
}
};
db.collection("data").doc("one").set(docData).then(() => {
console.log("Document successfully written!");
});
// [END data_types]
});
it("should allow set with merge", () => {
// [START set_with_merge]
var cityRef = db.collection('cities').doc('BJ');
var setWithMerge = cityRef.set({
capital: true
}, { merge: true });
// [END set_with_merge]
return setWithMerge;
});
it("should update a document's nested fields #UNVERIFIED", () => {
// [START update_document_nested]
// Create an initial document to update.
var frankDocRef = db.collection("users").doc("frank");
frankDocRef.set({
name: "Frank",
favorites: { food: "Pizza", color: "Blue", subject: "recess" },
age: 12
});
// To update age and favorite color:
db.collection("users").doc("frank").update({
"age": 13,
"favorites.color": "Red"
})
.then(() => {
console.log("Document successfully updated!");
});
// [END update_document_nested]
});
it("should delete a collection", () => {
// [START delete_collection]
/**
* Delete a collection, in batches of batchSize. Note that this does
* not recursively delete subcollections of documents in the collection
*/
function deleteCollection(db, collectionRef, batchSize) {
var 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
var batch = db.batch();
snapshot.docs.forEach((doc) => {
batch.delete(doc.ref);
});
return batch.commit().then(() => {
return snapshot.size;
});
}).then((numDeleted) => {
if (numDeleted < batchSize) {
resolve();
return;
}
// Recurse on the next process tick, to avoid
// exploding the stack.
setTimeout(() => {
deleteQueryBatch(db, query, batchSize, resolve, reject);
}, 0);
})
.catch(reject);
}
// [END delete_collection]
return deleteCollection(db, db.collection("users"), 2);
}).timeout(2000);
});
describe("collection('cities')", () => {
it("should set documents #UNVERIFIED", () => {
// [START example_data]
var citiesRef = db.collection("cities");
citiesRef.doc("SF").set({
name: "San Francisco", state: "CA", country: "USA",
capital: false, population: 860000,
regions: ["west_coast", "norcal"] });
citiesRef.doc("LA").set({
name: "Los Angeles", state: "CA", country: "USA",
capital: false, population: 3900000,
regions: ["west_coast", "socal"] });
citiesRef.doc("DC").set({
name: "Washington, D.C.", state: null, country: "USA",
capital: true, population: 680000,
regions: ["east_coast"] });
citiesRef.doc("TOK").set({
name: "Tokyo", state: null, country: "Japan",
capital: true, population: 9000000,
regions: ["kanto", "honshu"] });
citiesRef.doc("BJ").set({
name: "Beijing", state: null, country: "China",
capital: true, population: 21500000,
regions: ["jingjinji", "hebei"] });
// [END example_data]
});
it("should set a document", () => {
var data = {};
var output =
// [START cities_document_set]
db.collection("cities").doc("new-city-id").set(data);
// [END cities_document_set]
return output;
});
it("should add a document", () => {
var output =
// [START add_document]
// Add a new document with a generated id.
db.collection("cities").add({
name: "Tokyo",
country: "Japan"
})
.then((docRef) => {
console.log("Document written with ID: ", docRef.id);
})
.catch((error) => {
console.error("Error adding document: ", error);
});
// [END add_document]
return output;
});
it("should add an empty a document #UNVERIFIED", () => {
var data = {};
// [START new_document]
// Add a new document with a generated id.
var newCityRef = db.collection("cities").doc();
// later...
newCityRef.set(data);
// [END new_document]
});
it("should update a document", () => {
var data = {};
// [START update_document]
var washingtonRef = db.collection("cities").doc("DC");
// Set the "capital" field of the city 'DC'
return washingtonRef.update({
capital: true
})
.then(() => {
console.log("Document successfully updated!");
})
.catch((error) => {
// The document probably doesn't exist.
console.error("Error updating document: ", error);
});
// [END update_document]
});
it("should update an array field in a document", () => {
// [START update_document_array]
var washingtonRef = db.collection("cities").doc("DC");
// Atomically add a new region to the "regions" array field.
washingtonRef.update({
regions: firebase.firestore.FieldValue.arrayUnion("greater_virginia")
});
// Atomically remove a region from the "regions" array field.
washingtonRef.update({
regions: firebase.firestore.FieldValue.arrayRemove("east_coast")
});
// [END update_document_array]
});
it("should update a document using numeric transforms", () => {
// [START update_document_increment]
var washingtonRef = db.collection('cities').doc('DC');
// Atomically increment the population of the city by 50.
washingtonRef.update({
population: firebase.firestore.FieldValue.increment(50)
});
// [END update_document_increment]
});
it("should delete a document", () => {
var output =
// [START delete_document]
db.collection("cities").doc("DC").delete().then(() => {
console.log("Document successfully deleted!");
}).catch((error) => {
console.error("Error removing document: ", error);
});
// [END delete_document]
return output;
});
it("should handle transactions #FIXME #UNVERIFIED", () => {
return db.collection("cities").doc("SF").set({ population: 0 }).then(() => {
// [START transaction]
// Create a reference to the SF doc.
var sfDocRef = db.collection("cities").doc("SF");
// Uncomment to initialize the doc.
// sfDocRef.set({ population: 0 });
return db.runTransaction((transaction) => {
// This code may get re-run multiple times if there are conflicts.
return transaction.get(sfDocRef).then((sfDoc) => {
if (!sfDoc.exists) {
throw "Document does not exist!";
}
// Add one person to the city population.
// Note: this could be done without a transaction
// by updating the population using FieldValue.increment()
var newPopulation = sfDoc.data().population + 1;
transaction.update(sfDocRef, { population: newPopulation });
});
}).then(() => {
console.log("Transaction successfully committed!");
}).catch((error) => {
console.log("Transaction failed: ", error);
});
// [END transaction]
});
});
it("should handle transaction which bubble out data #UNVERIFIED", () => {
// [START transaction_promise]
// Create a reference to the SF doc.
var sfDocRef = db.collection("cities").doc("SF");
db.runTransaction((transaction) => {
return transaction.get(sfDocRef).then((sfDoc) => {
if (!sfDoc.exists) {
throw "Document does not exist!";
}
var newPopulation = sfDoc.data().population + 1;
if (newPopulation <= 1000000) {
transaction.update(sfDocRef, { population: newPopulation });
return newPopulation;
} else {
return Promise.reject("Sorry! Population is too big.");
}
});
}).then((newPopulation) => {
console.log("Population increased to ", newPopulation);
}).catch((err) => {
// This will be an "population is too big" error.
console.error(err);
});
// [END transaction_promise]
});
it("should get a single document #UNVERIFIED", () => {
// [START get_document]
var docRef = db.collection("cities").doc("SF");
docRef.get().then((doc) => {
if (doc.exists) {
console.log("Document data:", doc.data());
} else {
// doc.data() will be undefined in this case
console.log("No such document!");
}
}).catch((error) => {
console.log("Error getting document:", error);
});
// [END get_document]
});
it("should get a document with options #UNVERIFIED", () => {
// [START get_document_options]
var docRef = db.collection("cities").doc("SF");
// Valid options for source are 'server', 'cache', or
// 'default'. See https://firebase.google.com/docs/reference/js/v8/firebase.firestore.GetOptions
// for more information.
var getOptions = {
source: 'cache'
};
// Get a document, forcing the SDK to fetch from the offline cache.
docRef.get(getOptions).then((doc) => {
// Document was found in the cache. If no cached document exists,
// an error will be returned to the 'catch' block below.
console.log("Cached document data:", doc.data());
}).catch((error) => {
console.log("Error getting cached document:", error);
});
// [END get_document_options]
});
it("should listen on a single document", (done) => {
var unsub =
// [START listen_document]
db.collection("cities").doc("SF")
.onSnapshot((doc) => {
console.log("Current data: ", doc.data());
});
// [END listen_document]
setTimeout(() => {
unsub();
done();
}, 3000);
}).timeout(5000);
it("should listen on a single document with metadata #UNVERIFIED", (done) => {
var unsub =
// [START listen_document_local]
db.collection("cities").doc("SF")
.onSnapshot((doc) => {
var source = doc.metadata.hasPendingWrites ? "Local" : "Server";
console.log(source, " data: ", doc.data());
});
// [END listen_document_local]
setTimeout(() => {
unsub();
done();
}, 3000);
}).timeout(5000);
it("should listen on a single document with options #UNVERIFIED", (done) => {
var unsub =
// [START listen_with_metadata]
db.collection("cities").doc("SF")
.onSnapshot({
// Listen for document metadata changes
includeMetadataChanges: true
}, (doc) => {
// ...
});
// [END listen_with_metadata]
setTimeout(() => {
unsub();
done();
}, 3000);
}).timeout(5000);
it("should get multiple documents from a collection", () => {
var output =
// [START get_multiple]
db.collection("cities").where("capital", "==", true)
.get()
.then((querySnapshot) => {
querySnapshot.forEach((doc) => {
// doc.data() is never undefined for query doc snapshots
console.log(doc.id, " => ", doc.data());
});
})
.catch((error) => {
console.log("Error getting documents: ", error);
});
// [END get_multiple]
return output;
}).timeout(5000);
it("should get all documents from a collection", () => {
var output =
// [START get_multiple_all]
db.collection("cities").get().then((querySnapshot) => {
querySnapshot.forEach((doc) => {
// doc.data() is never undefined for query doc snapshots
console.log(doc.id, " => ", doc.data());
});
});
// [END get_multiple_all]
return output;
});
it("should listen on multiple documents #UNVERIFIED", (done) => {
var unsubscribe =
// [START listen_multiple]
db.collection("cities").where("state", "==", "CA")
.onSnapshot((querySnapshot) => {
var cities = [];
querySnapshot.forEach((doc) => {
cities.push(doc.data().name);
});
console.log("Current cities in CA: ", cities.join(", "));
});
// [END listen_multiple]
setTimeout(() => {
unsubscribe();
done();
}, 2500);
}).timeout(5000);
it("should view changes between snapshots #UNVERIFIED", (done) => {
var unsubscribe =
// [START listen_diffs]
db.collection("cities").where("state", "==", "CA")
.onSnapshot((snapshot) => {
snapshot.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());
}
});
});
// [END listen_diffs]
setTimeout(() => {
unsubscribe();
done();
}, 2500);
}).timeout(5000);
it("should unsubscribe a listener", () => {
// [START detach_listener]
var unsubscribe = db.collection("cities")
.onSnapshot(() => {
// Respond to data
// ...
});
// Later ...
// Stop listening to changes
unsubscribe();
// [END detach_listener]
});
it("should handle listener errors", () => {
var unsubscribe =
// [START handle_listen_errors]
db.collection("cities")
.onSnapshot((snapshot) => {
// ...
}, (error) => {
// ...
});
// [END handle_listen_errors]
unsubscribe();
});
it("should update a document with server timestamp", () => {
function update() {
// [START update_with_server_timestamp]
var docRef = db.collection('objects').doc('some-id');
// Update the timestamp field with the value from the server
var updateTimestamp = docRef.update({
timestamp: firebase.firestore.FieldValue.serverTimestamp()
});
// [END update_with_server_timestamp]
return updateTimestamp;
}
return db.collection('objects').doc('some-id')
.set({})
.then(() => update())
.then(() => {
console.log('Document updated with server timestamp');
});
});
it("should use options to control server timestamp resolution #UNVERIFIED", () => {
var options = {
// Options: 'estimate', 'previous', or 'none'
serverTimestamps: 'estimate'
};
// Perform an update followed by an immediate read without
// waiting for the update to complete. Due to the snapshot
// options we will get two results: one with an estimate
// timestamp and one with the resolved server timestamp.
var docRef = db.collection('objects').doc('some-id');
docRef.update({
timestamp: firebase.firestore.FieldValue.serverTimestamp()
});
docRef.onSnapshot((snapshot) => {
var data = snapshot.data(options);
console.log(
'Timestamp: ' + data.timestamp +
', pending: ' + snapshot.metadata.hasPendingWrites);
});
});
it("should delete a document field", () => {
function update() {
// [START update_delete_field]
var cityRef = db.collection('cities').doc('BJ');
// Remove the 'capital' field from the document
var removeCapital = cityRef.update({
capital: firebase.firestore.FieldValue.delete()
});
// [END update_delete_field]
return removeCapital;
}
return db.collection('cities').doc('BJ')
.set({ capital: true })
.then(() => update())
.then(() => {
console.log('Document field deleted');
});
});
describe("queries", () => {
it("should handle simple where", () => {
// [START simple_queries]
// Create a reference to the cities collection
var citiesRef = db.collection("cities");
// Create a query against the collection.
var query = citiesRef.where("state", "==", "CA");
// [END simple_queries]
});
it("should handle another simple where", () => {
// [START simple_queries_again]
var citiesRef = db.collection("cities");
var query = citiesRef.where("capital", "==", true);
// [END simple_queries_again]
});
it("should handle other wheres", () => {
var citiesRef = db.collection("cities");
// [START example_filters]
const stateQuery = citiesRef.where("state", "==", "CA");
const populationQuery = citiesRef.where("population", "<", 100000);
const nameQuery = citiesRef.where("name", ">=", "San Francisco");
// [END example_filters]
// [START simple_query_not_equal]
citiesRef.where("capital", "!=", false);
// [END simple_query_not_equal]
});
it("should handle array-contains where", () => {
var citiesRef = db.collection("cities");
// [START array_contains_filter]
citiesRef.where("regions", "array-contains", "west_coast");
// [END array_contains_filter]
});
it("should handle an array contains any where", () => {
const citiesRef = db.collection('cities');
// [START array_contains_any_filter]
citiesRef.where('regions', 'array-contains-any',
['west_coast', 'east_coast']);
// [END array_contains_any_filter]
});
it("should handle an in where", () => {
const citiesRef = db.collection('cities');
// [START in_filter]
citiesRef.where('country', 'in', ['USA', 'Japan']);
// [END in_filter]
// [START not_in_filter]
citiesRef.where('country', 'not-in', ['USA', 'Japan']);
// [END not_in_filter]
// [START in_filter_with_array]
citiesRef.where('regions', 'in',
[['west_coast'], ['east_coast']]);
// [END in_filter_with_array]
});
it("should handle compound queries", () => {
var citiesRef = db.collection("cities");
// [START chain_filters]
const q1 = citiesRef.where("state", "==", "CO").where("name", "==", "Denver");
const q2 = citiesRef.where("state", "==", "CA").where("population", "<", 1000000);
// [END chain_filters]
});
it("should handle range filters on one field", () => {
var citiesRef = db.collection("cities");
// [START valid_range_filters]
const q1 = citiesRef.where("state", ">=", "CA").where("state", "<=", "IN");
const q2 = citiesRef.where("state", "==", "CA").where("population", ">", 1000000);
// [END valid_range_filters]
});
it("should not handle range filters on multiple field", () => {
var citiesRef = db.collection("cities");
expect(() => {
// [START invalid_range_filters]
citiesRef.where("state", ">=", "CA").where("population", ">", 100000);
// [END invalid_range_filters]
}).to.throw();
});
it("should order and limit", () => {
var citiesRef = db.collection("cities");
// [START order_and_limit]
citiesRef.orderBy("name").limit(3);
// [END order_and_limit]
});
it("should order descending", () => {
var citiesRef = db.collection("cities");
// [START order_and_limit_desc]
citiesRef.orderBy("name", "desc").limit(3);
// [END order_and_limit_desc]
});
it("should order descending by other field", () => {
var citiesRef = db.collection("cities");
// [START order_multiple]
citiesRef.orderBy("state").orderBy("population", "desc");
// [END order_multiple]
});
it("should where and order by with limit", () => {
var citiesRef = db.collection("cities");
// [START filter_and_order]
citiesRef.where("population", ">", 100000).orderBy("population").limit(2);
// [END filter_and_order]
});
it("should where and order on same field", () => {
var citiesRef = db.collection("cities");
// [START valid_filter_and_order]
citiesRef.where("population", ">", 100000).orderBy("population");
// [END valid_filter_and_order]
});
it("should not where and order on same field", () => {
var citiesRef = db.collection("cities");
expect(() => {
// [START invalid_filter_and_order]
citiesRef.where("population", ">", 100000).orderBy("country");
// [END invalid_filter_and_order]
}).to.throw;
});
it("should handle startAt", () => {
var citiesRef = db.collection("cities");
// [START order_and_start]
citiesRef.orderBy("population").startAt(1000000);
// [END order_and_start]
});
it("should handle endAt", () => {
var citiesRef = db.collection("cities");
// [START order_and_end]
citiesRef.orderBy("population").endAt(1000000);
// [END order_and_end]
});
it("should handle startAt(doc) ", () => {
// [START start_doc]
var citiesRef = db.collection("cities");
return citiesRef.doc("SF").get().then((doc) => {
// Get all cities with a population bigger than San Francisco
var biggerThanSf = citiesRef
.orderBy("population")
.startAt(doc);
// ...
});
// [END start_doc]
});
it("should handle multiple orderBy", () => {
// [START start_multiple_orderby]
// Will return all Springfields