Firebase:交易读取和更新多个文档

时间:2018-04-29 14:24:28

标签: javascript firebase google-cloud-firestore

使用此代码,我可以在事务中读取和更新单个文档。

// 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 });

问题: 但我需要阅读并更新多个文档,并根据其内容更新每个文档。例如,我想在我的代码中更新帖子集合中的喜欢数量,但也更新我的个人资料文档中的总喜欢数量。

2 个答案:

答案 0 :(得分:2)

要更新交易中的多个文档,请多次调用t.update()

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

答案 1 :(得分:0)

您可以使用batch来完成您想要的任务。

var batch = db.batch();

var docRef = admin
  .firestore()
  .collection("posts")
  .doc(doc_id);

var likes = ... // get the amount of likes

batch.update(docRef, { likes })

var profileRef = admin
  .firestore()
  .collection('profile')
  .doc(profId)
batch.update(profileRef, { likes })

batch.commit() // at this point everything works or not
  .then(() => {
    console.log('success!')
  })
  .catch(err => {
    console.log('something went wrong')
  })