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

问题描述:

我想在firestore中执行批量事务。我将最后一个密钥存储在其他收藏中。 我需要得到最后一个键然后增加1,然后使用这个键创建两个文档。我怎样才能做到这一点?如何在使用批处理时从Firestore获取数据?

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

如果您想在单个操作中读取/写入数据,您应该使用事务。

// 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

+0

但是有一点需要注意 - 交易目前不支持离线,我希望将在未来改变:) –