Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- var db = firebase.firestore();
- //From the Firebase documentation
- function createCounter(ref, num_shards) {
- var batch = db.batch();
- // Initialize the counter document
- batch.set(ref, { num_shards: num_shards });
- // Initialize each shard with count=0
- for (let i = 0; i < num_shards; i++) {
- let shardRef = ref.collection('shards').doc(i.toString());
- batch.set(shardRef, { count: 0 });
- }
- // Commit the write batch
- return batch.commit();
- }
- function incrementCounter(db, ref, num_shards) {
- // Select a shard of the counter at random
- const shard_id = Math.floor(Math.random() * num_shards).toString();
- const shard_ref = ref.collection('shards').doc(shard_id);
- // Update count
- return shard_ref.update(
- 'count',
- firebase.firestore.FieldValue.increment(1)
- );
- }
- function getCount(ref) {
- // Sum the count of each shard in the subcollection
- return ref
- .collection('shards')
- .get()
- .then(snapshot => {
- let total_count = 0;
- snapshot.forEach(doc => {
- total_count += doc.data().count;
- });
- return total_count;
- });
- }
- //Your code
- var ref = firebase
- .firestore()
- .collection('counters')
- .doc('1');
- var num_shards = 2 //Adapt as required, read the doc
- //Initialize the counter bay calling ONCE the createCounter() method
- createCounter(ref, num_shards);
- //Then, when you want to create a new number and a new doc you do
- incrementCounter(db, ref, num_shards)
- .then(() => {
- return getCount(ref);
- })
- .then(count => {
- console.log(count);
- //Here you get the new number form the sequence
- //And you use it to create a doc
- db.collection("events").doc(count.toString()).set({
- category: "education",
- //....
- })
- });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement