Firestore事务在单个事务中更新多个文档 [英] Firestore transaction update multiple documents in a single transaction

查看:118
本文介绍了Firestore事务在单个事务中更新多个文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何通过使用我搜索的单个事务更新firestore中的多个文档,但我没有得到任何答案。是否可以在单个交易中更新多个文档?我知道它可以通过批量写入来完成。

How can i update multiple documents in firestore by using a single transaction i searched but i didn't get any answers. Is it possible to update multiple documents in a single transaction? I know it can be done by batch writes.

推荐答案

我想通了我们可以在事务中使用多个ref:

I figured it out we can use multiple ref inside a transaction:

var userSuhail = db.collection("users").doc("suhail");
var userSam = db.collection("users").doc("sam");
var userJohn = db.collection("users").doc("john");
var userAlfred = db.collection("users").doc("Alfred");
var userAlfredDetails = db.collection('userdetails').doc('Alfred');

db.runTransaction(function (transaction) {
  return transaction.get(userJohn).then(function (sDoc) {
    var age = sDoc.data().age + 1;
    transaction.set(userAlfred, { name: 'Alfred', age: age, details: userAlfredDetails });
    transaction.set(userAlfredDetails, { address: 'Alfred Villa' });
    transaction.update(userJohn, {
      age: age
    });
    transaction.update(userSuhail, {
      age: age
    });
    transaction.update(userSam, {
      age: age
    });
    return age;
  });
}).then(function (age) {
  console.log("Age changed to ", age);
}).catch(function (err) {

  console.error(err);
});

通过上面的代码,交易更新了所有用户的年龄。

By the above code the transaction updates age of all users.

这篇关于Firestore事务在单个事务中更新多个文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆