Firebase:事务读取和更新多个文档 [英] Firebase: Transaction read and update multiple documents
本文介绍了Firebase:事务读取和更新多个文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
使用此代码,我可以读取和更新交易中的单个文档.
With this code I can read and update single document in the transaction.
// Update likes in post
var docRef = admin
.firestore()
.collection("posts")
.doc(doc_id);
let post = await admin.firestore().runTransaction(t => t.get(docRef));
if (!post.exists) {
console.log("post not exist")
}
postData = { ...post.data(), id: post.id };
let likes = postData.likes || 0;
var newLikes = likes + 1;
await post.ref.update({ likes: newLikes });
问题:但是我需要阅读和更新多个文档,每个文档都根据其内容进行更新.例如,我想像我的代码一样更新帖子集合中的点赞次数,但也要更新个人资料文档中的总点赞次数.
Question: But I need to read and update multiple documents and each one update depending on their content. For example I want to update number of likes in posts collection as in my code but also update number of total likes in my profile document.
推荐答案
要更新事务中的多个文档,请多次调用 t.update()
.
To update multiple documents in a transaction, you call t.update()
multiple times.
let promise = await admin.firestore().runTransaction(transaction => {
var post = transaction.get(docRef);
var anotherPost = transaction.get(anotherDocRef);
if (post.exists && anotherPost.exists) {
var newLikes = (post.data().likes || 0) + 1;
await transaction.update(docRef, { likes: newLikes });
newLikes = (anotherPost.data().likes || 0) + 1;
await transaction.update(anotherdocRef, { likes: newLikes });
}
})
请参见 https://firebase.google.com/docs/firestore/manage-data/transactions#transactions
这篇关于Firebase:事务读取和更新多个文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文