简体   繁体   English

Firebase:事务读取和更新多个文档

[英]Firebase: Transaction read and update multiple documents

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. 例如,我想像我的代码一样更新帖子集合中的点赞次数,但也要更新我的个人资料文档中的总点赞次数。

To update multiple documents in a transaction, you call t.update() multiple times. 要更新事务中的多个文档,请多次调用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 });
  }
})

See https://firebase.google.com/docs/firestore/manage-data/transactions#transactions 请参阅https://firebase.google.com/docs/firestore/manage-data/transactions#transactions

You can use batch to accomplish what you want. 您可以使用批处理来完成所需的操作。

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')
  })

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM