类型错误:querySnapshot.forEach 不是函数 - Firebase Cloud Functions

Sta*_*kGU 9 javascript firebase google-cloud-platform google-cloud-functions google-cloud-firestore

我有一个这样的数据结构:

  • 帖子(收藏)
  • 用户ID(文档)
  • 帖子(收藏)
  • 博士后(文档)

我正在设置一个云函数来根据特定事件更改所有帖子(子集合)文档,为此我使用collectionGroup查询:

我是这样设置的:

exports.changeIsVisibleFieldAfterDay = functions.pubsub
.schedule("every 2 minutes").onRun((context) => {
  const querySnapshot = db.collectionGroup("Posts")
      .where("isVisible", "==", true).get();
  querySnapshot.forEach((doc) => {
    console.log(doc.data());
  });
});
Run Code Online (Sandbox Code Playgroud)

Firebase Log我收到以下错误:

TypeError: querySnapshot.forEach is not a function
Run Code Online (Sandbox Code Playgroud)

网上搜索发现Firebase SDK版本可能有问题,但我的是最新的,我package.json在这里附上文件:

{
  "name": "functions",
  "description": "Cloud Functions for Firebase",
  "scripts": {
    "lint": "eslint .",
    "serve": "firebase emulators:start --only functions",
    "shell": "firebase functions:shell",
    "start": "npm run shell",
    "deploy": "firebase deploy --only functions",
    "logs": "firebase functions:log"
  },
  "engines": {
    "node": "12"
  },
  "main": "index.js",
  "dependencies": {
    "firebase-admin": "^9.2.0",
    "firebase-functions": "^3.11.0"
  },
  "devDependencies": {
    "eslint": "^7.6.0",
    "eslint-config-google": "^0.14.0",
    "firebase-functions-test": "^0.2.0"
  },
  "private": true
}
Run Code Online (Sandbox Code Playgroud)

Ren*_*nec 11

get()方法是异步的,因此您需要使用then()来获取何时满足querySnapshot返回的 Promise ,或者使用. 有关如何处理异步调用的更多详细信息,请参阅此SO 答案get()async/await

then()

const functions = require('firebase-functions');

// The Firebase Admin SDK to access Firestore.
const admin = require('firebase-admin');
admin.initializeApp();

const db = admin.firestore();

exports.changeIsVisibleFieldAfterDay = functions.pubsub
.schedule("every 2 minutes").onRun((context) => {
  return db.collectionGroup("Posts").where("isVisible", "==", true).get()
  .then(querySnapshot => {
     querySnapshot.forEach((doc) => {
      console.log(doc.data());
     });
     return null;
  })
});
Run Code Online (Sandbox Code Playgroud)

async/await

const functions = require('firebase-functions');

// The Firebase Admin SDK to access Firestore.
const admin = require('firebase-admin');
admin.initializeApp();

const db = admin.firestore();

exports.changeIsVisibleFieldAfterDay = functions.pubsub
.schedule("every 2 minutes").onRun(async (context) => {
  const querySnapshot = await db.collectionGroup("Posts").where("isVisible", "==", true).get();
  querySnapshot.forEach((doc) => {
     console.log(doc.data());
  });
  return null;
});
Run Code Online (Sandbox Code Playgroud)

注意return null;最后的。有关此关键点的更多详细信息,请参阅此文档项。


另请注意,如果您想更新forEach()循环内的多个文档,则需要使用Promise.all(). 许多 SO 答案都涵盖了这种情况。