TypeError: undefined is not iterable (cannot read property Symbol(Symbol.iterator)) at Function.all (<anonymous>) Firebase Cloud Function

时间:2021-02-02 22:36:13

标签: firebase google-cloud-firestore google-cloud-functions

我是这样设置云功能的:

exports.changeIsVisibleFieldAfterDay = functions.pubsub
.schedule("every 2 minutes").onRun((context) => {
  const d = new Date();
  d.setDate(d.getDate() - 1);
  return db.collectionGroup("Moments")
      .where("isVisible", "==", true)
      .where("timestamp", "<=", d)
      .get()
      .then((querySnapshot) => {
        querySnapshot.forEach((doc) => {
          Promise.all().doc.ref.update({isVisible: false}, {merge: true});
        });
        return null;
      });
});

当我插入 Promise.all() 以更新子集合中的所有文档时,我收到此错误:

TypeError: undefined is not iterable (cannot read property Symbol(Symbol.iterator))
at Function.all (<anonymous>) 

当我不使用 Promise.all() 时,文档会正确更新,但我知道如果我想更新大量文档,我需要一个 Promise

1 个答案:

答案 0 :(得分:2)

根据 Mozilla JS referencepromise.All 函数在输入时需要一组承诺,因为您没有提供一个承诺,错误警告您未定义(即没有参数)不可迭代.

实际上你想要的是类似于下面的代码(已经过测试):

db.collectionGroup("Moments")
    .where("isVisible", "==", true)
    .where("timestamp", "<=", d)
    .get()
    .then((querySnap) => {
        // Create an array of the promises returned by update()
        let promises = [];
        querySnap.forEach((doc) => {
            promises.push(doc.ref.update({hello:"yes"}, {merge: true}))
        });
        // Resolve the promises
        Promise.all(promises)
            .then((x) => console.log("Docs updated"))
            .catch((err) => console.error(err));
    });