如何在使用批处理时从 firestore 获取数据?

How to get a data from firestore while using batch?

我想在 firestore 中执行批量交易。我将最后一个密钥存储在其他集合中。 我需要得到最后一个密钥然后增加 1,然后使用这个密钥创建两个文档。我该怎么做?

 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') })

如果您想 read/write 在单个操作中获取数据,您应该使用事务。

// 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);
});

您可以在此处阅读有关交易和批次的更多信息: https://firebase.google.com/docs/firestore/manage-data/transactions