Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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

Post a Comment for "Firebase: Transaction Read And Update Multiple Documents"