Advertisement
Guest User

Untitled

a guest
Jun 18th, 2019
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.83 KB | None | 0 0
  1. var db = firebase.firestore();
  2.  
  3. //From the Firebase documentation
  4.  
  5. function createCounter(ref, num_shards) {
  6. var batch = db.batch();
  7.  
  8. // Initialize the counter document
  9. batch.set(ref, { num_shards: num_shards });
  10.  
  11. // Initialize each shard with count=0
  12. for (let i = 0; i < num_shards; i++) {
  13. let shardRef = ref.collection('shards').doc(i.toString());
  14. batch.set(shardRef, { count: 0 });
  15. }
  16.  
  17. // Commit the write batch
  18. return batch.commit();
  19. }
  20.  
  21. function incrementCounter(db, ref, num_shards) {
  22. // Select a shard of the counter at random
  23. const shard_id = Math.floor(Math.random() * num_shards).toString();
  24. const shard_ref = ref.collection('shards').doc(shard_id);
  25.  
  26. // Update count
  27. return shard_ref.update(
  28. 'count',
  29. firebase.firestore.FieldValue.increment(1)
  30. );
  31. }
  32.  
  33. function getCount(ref) {
  34. // Sum the count of each shard in the subcollection
  35. return ref
  36. .collection('shards')
  37. .get()
  38. .then(snapshot => {
  39. let total_count = 0;
  40. snapshot.forEach(doc => {
  41. total_count += doc.data().count;
  42. });
  43.  
  44. return total_count;
  45. });
  46. }
  47.  
  48. //Your code
  49.  
  50. var ref = firebase
  51. .firestore()
  52. .collection('counters')
  53. .doc('1');
  54.  
  55. var num_shards = 2 //Adapt as required, read the doc
  56.  
  57. //Initialize the counter bay calling ONCE the createCounter() method
  58.  
  59. createCounter(ref, num_shards);
  60.  
  61. //Then, when you want to create a new number and a new doc you do
  62.  
  63. incrementCounter(db, ref, num_shards)
  64. .then(() => {
  65. return getCount(ref);
  66. })
  67. .then(count => {
  68. console.log(count);
  69. //Here you get the new number form the sequence
  70. //And you use it to create a doc
  71. db.collection("events").doc(count.toString()).set({
  72. category: "education",
  73. //....
  74. })
  75. });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement