【问题标题】:angular batch update not working to firebase角度批量更新不适用于firebase
【发布时间】:2022-10-13 19:27:35
【问题描述】:

我创建了一个名为newOrder 的多维数组:

0: {id: 'JNuxJewf4E8YyX7t3fPk', order: 2000}
1: {id: 's2kCZnF5vhp1E6cW3VXI', order: 3000}
2: {id: 'UGPPNa7zTuUkBmuorF2v', order: 4000}
3: {id: '0YzyArRPQQ3ZyAOfOJjM', order: 5000}
4: {id: 'LpZnzX6NufWsaVQ52lyS', order: 6000}
5: {id: 'VfL8pX77LCxXniWQunk7', order: 7000}
6: {id: '8QtF3CbpVjIXeI4ziHxy', order: 8000}
7: {id: 'y05y6Hta6kesXymg034Q', order: 9000}
8: {id: 'LQPq6q3Dp6CeACTiO8IC', order: 10000}
9: {id: 'bmeT3h3kG7Oeilf0nIQ8', order: 11000}
10:{id: 'mrHFK2wEsn9UhFz5AOEQ', order: 12000}

我正在尝试循环浏览它们并使用id: 更新每条记录中的order: 字段。到目前为止,我已经读到批量更新是要走的路。所以我写了以下内容:

const batch = this.fireStore.firestore.batch();
this.newOrder.forEach((val, index) => {
  const id = this.newOrder[index]['id'];
  const orderNum = this.newOrder[index]['order'];
  console.log (' id:' + id + ' order:' + orderNum);
  const pageRef = this.fireStore.doc('content/${id}').ref;
  batch.update(pageRef, {order:orderNum});
});

我没有收到任何错误,并且控制台日志输出正确,但它没有更新 firebase 记录。我究竟做错了什么?我已经在这里待了2天了。

【问题讨论】:

    标签: angular typescript firebase


    【解决方案1】:

    从您的代码看来,您错过了对commit() 的调用。一旦批处理中的所有写入作为原子单元成功写入后端,此异步方法将返回已解决的 Promise。

    const batch = this.fireStore.firestore.batch();
    this.newOrder.forEach((val, index) => {
      const id = this.newOrder[index]['id'];
      const orderNum = this.newOrder[index]['order'];
      console.log (' id:' + id + ' order:' + orderNum);
      const pageRef = this.fireStore.doc(`content/${id}`).ref;
      batch.update(pageRef, {order:orderNum});
    });
    batch.commit()
    .then( => {  // ... If necessary  });
    

    【讨论】:

    • 那太好了。太感谢了。我不知道需要提交。我还需要将'content/${id}' 更改为content/${id},(引用类型),以便它接受动态ID。 (我无法在此处显示倾斜的报价)
    • 很高兴我能帮助你。我没有看到您的模板文字中缺少反引号 (`) 字符:-) 答案已适应。
    猜你喜欢
    • 2020-11-30
    • 1970-01-01
    • 2020-05-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-13
    相关资源
    最近更新 更多