【问题标题】:How to update document from a collection whenever another document in another collection is created with Firebase functions?每当使用 Firebase 函数创建另一个集合中的另一个文档时,如何从集合中更新文档?
【发布时间】:2019-09-18 08:01:59
【问题描述】:

因此,每当创建新销售时,我都会尝试更新项目余额,因此我正在监听该销售创建并获取所有项目以检查新销售和项目之间的匹配 ID 并更新其余额

功能已部署,但物品余额没有任何变化

 export const itemsBalance = functions.firestore

.document("sales/{id}")
.onCreate((snap, context) => {
  //get sale data and items data
  const data = snap.data();

  //get all items
  let myItems;
  firebase.firestore().collection('items').get()
  .then(snapshot => {
      myItems = snapshot.docs.map(doc => doc.data());

      data.items.forEach((element, index) => {
          let updatedItem = myItems.find(el => el.id == element.id);
          if(updatedItem) {
              updatedItem.balance = updatedItem.balance - element.qty;
          }



          firebase.firestore().collection(`items/${element.id}`)
          .doc().update(updatedItem)
          .then(res => console.log(res))
          .catch(err => console.log(err));
          })
        })
        .catch(err => {
          console.log(err)
        })
      return data;
   });

package.json

  "dependencies": {
    "firebase-admin": "^7.3.0",
    "firebase-functions": "^2.3.0"
   }

【问题讨论】:

    标签: node.js firebase google-cloud-firestore google-cloud-functions


    【解决方案1】:

    当所有异步工作完全完成时,您不会返回一个解决方案。您需要获取从 update() 返回的所有 Promise,将它们推送到一个数组中,并在该数组上使用 Promise.all() 来生成一个新的 Promise,该 Promise 将在所有工作完成后解决。从函数中返回该承诺。

    另见:

    【讨论】:

    • const p = firebase.firestore().collection(items/${element.id}).doc().update(updatedItem) promises.push(p); }) return Promise.all(promises);
    • 但我的物品也没有改变余额
    猜你喜欢
    • 2012-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多