gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 23:38:26 24 4
gpt4 key购买 nike

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

最佳答案

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

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

关于firebase - 使用批处理时如何从firestore获取数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46790459/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com