2017-10-17 58 views
1

我想在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') }) 

回答

3

如果您想在單個操作中讀取/寫入數據,您應該使用事務。

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

但是有一點需要注意 - 交易目前不支持離線,我希望將在未來改變:) –