Firebase: Transaction read and update multiple documents

后端 未结 2 2019
小蘑菇
小蘑菇 2021-01-21 20:16

With this code I can read and update single document in the transaction.

// Update likes in post
var docRef = admin
  .firestore()
  .collection(\"posts\")
  .do         


        
相关标签:
2条回答
  • 2021-01-21 21:02

    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')
      })
    
    0 讨论(0)
  • 2021-01-21 21:03

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

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

    0 讨论(0)
提交回复
热议问题