【发布时间】:2018-01-15 16:13:01
【问题描述】:
对于上下文:我有一个 cron-job.org,它在我的 firebase 项目中触发 https 函数。
在这个函数中,我必须遍历集合中的所有文档并更新一个计数器(每个文档可能有不同的计数器值)。如果计数器达到限制,我将更新另一个集合(独立于第一个集合),并删除达到限制的文档条目。如果计数器没有超出限制,我只需使用更新后的计数器值更新文档条目。
我尝试改编文档中的示例,尝试使用事务、批处理,但我不确定如何继续。根据事务的描述,这是要走的路,但示例仅显示如何编辑单个文档。
这就是我所拥有的(尝试调整实时数据库样本):
function updateCounter() {
var ref = db.collection('my_collection_of_counters');
return ref.get().then(snapshot => {
const updates = {};
snapshot.forEach(child => {
var docData = child.data();
var newCounter = docData.counter+1;
if (newCounter == 10) {
// TO-DO: add to stock
updates[child.key] = null;
} else {
docData.counter = newCounter;
updates[child.key] = docData;
}
});
// execute all updates in one go and return the result to end the function
return ref.update(updates);
});
}
它不起作用,集合没有更新方法。更新集合中每个文档的最佳方法是什么?一个接一个?交易?有例子吗?
PS:updateCounter 是一个被 https 触发器调用的函数。 Cron+trigger 工作正常。
编辑 当一个项目达到阈值时,我想更新另一个集合,独立于计数器。嵌套事务是一个好的解决方案吗?
修改代码:
function updateCounter() {
var ref = db.collection('my_collection_of_counters');
var transaction = db.runTransaction(t => {
return t.get(ref)
.then(snapshot => {
let docs = snapshot.docs;
for (let doc of docs) {
var item = doc.data();
var newCounter = item.counter + 1;
if (newCounter == 10) {
console.log("Update my_stock");
// ADD item.quantity to stock collection
}else{
t.update(doc.ref, {counter: newCounter});
}
}
});
})
.then(result => {
console.log('Transaction success');
})
.catch(err => {
console.log('Transaction failure:', err);
});
}
【问题讨论】:
标签: javascript firebase transactions google-cloud-firestore