Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a data from firestore while using batch?

I want to perform a batch transaction in firestore. I am storing last key in other collection. i need to get the last key then increase by 1, then create two documents using this key. How can i do this?

 let lastDealKeyRef = this.db.collection('counters').doc('dealCounter')
 let dealsRef = this.db.collection('deals').doc(id)
 let lastDealKey = batch.get(lastDealKeyRef) // here is the problem..
 batch.set(dealsRef, dealData)
 let contentRef = this.db.collection('contents').doc('deal' + id)
 batch.set(contentRef, {'html': '<p>Hello World</p>' + lastDealKey })
 batch.commit().then(function () {
 console.log('done') })
like image 600
Prakash Bharti Avatar asked Jan 29 '23 09:01

Prakash Bharti


1 Answers

If you want to read/write data in a single operation you should be using a transaction.

// Set up all references
let lastDealKeyRef = this.db.collection('counters').doc('dealCounter');
let dealsRef = this.db.collection('deals').doc(id);
let contentRef = this.db.collection('contents').doc('deal' + id);


// Begin a transaction
db.runTransaction(function(transaction) {
    // Get the data you want to read
    return transaction.get(lastDealKeyRef).then(function(lastDealDoc) {
      let lastDealData = lastDealDoc.data();

      // Set all data
      let setDeals = transaction.set(dealsRef, dealData);
      let setContent = transaction.set(contentRef,  {'html': '<p>Hello World</p>' + lastDealKey });

      // Return a promise
      return Promise.all([setDeals, setContent]);

    });
}).then(function() {
    console.log("Transaction success.");
}).catch(function(err) {
    console.error("Transaction failure: " + err);
});

You can read more about transactions and batches here: https://firebase.google.com/docs/firestore/manage-data/transactions

like image 79
Sam Stern Avatar answered Feb 13 '23 07:02

Sam Stern