【问题标题】:Can Firestore Transactions Be Batched?Firestore 事务可以批量处理吗?
【发布时间】:2019-03-19 18:27:49
【问题描述】:

我对 Firestore 集合查询执行了一系列更新,其中每个更新都需要访问当前值。我知道事务是进行这些更新的原子方式,但是是否可以批量处理这一系列更新?

目前,我像这样更新集合:

let query;
query = db.collection('focuses');
query = query.where('userId', '==', auth.currentUser.uid);
query = query.where('active', '==', true);

query.get().then(snapshot => {
  const batch = db.batch();

  snapshot.forEach(doc => {
    batch.update(
      db.collection('focuses').doc(doc.id),
      { 
        active: false, 
        working: true,
        time: doc.data().workPeriod * 60,
      }
    );
  });

  batch.commit().then(() => {
    auth.signOut().catch(error => {
      console.error(error);
    });
  }).catch(error => {
    console.error(error);
  });
});

这可行,但 workPeriod 字段是在事务之外访问的,所以我的理解是它可能容易受到同时访问的影响。

那么是否可以为每个批量更新进行事务处理?如果不是,那么最好的方法是从一系列事务中收集每个Promise,然后使用Promise.all 设置将在一系列事务完成时调用的回调?

【问题讨论】:

    标签: javascript google-cloud-firestore


    【解决方案1】:

    不,交易不能批处理。您必须为原子更新选择批处理或事务。事务类似于批处理,因为所有更新都适用,或者它们都不适用。批处理和事务的区别在于,批处理只是写,而事务是先读后写。

    【讨论】:

      猜你喜欢
      • 2018-07-28
      • 2019-11-04
      • 2019-02-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-26
      • 2022-01-25
      相关资源
      最近更新 更多