代码之家  ›  专栏  ›  技术社区  ›  rendom

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

  •  2
  • rendom  · 技术社区  · 7 年前

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

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

    问题: 但我需要阅读和更新 倍数 文档和每个文档都会根据其内容进行更新。例如,我想在我的代码中更新帖子集合中的赞数,但也要更新我的个人资料文档中的总赞数。

    1 回复  |  直到 7 年前
        1
  •  4
  •   Frank van Puffelen    7 年前

    要更新事务中的多个文档,请调用 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