首页 > 解决方案 > 查询每个快照不是一个函数

问题描述

我在 Firebase 中部署了一个函数。Db 使用了 Firestore。进入日志时出错

Error getting documents:  TypeError: querySnapshot.forEach is not a function
    at /srv/lib/index.js:147:23
    at <anonymous>
    at process._tickDomainCallback (internal/process/next_tick.js:229:7)

试图从集合todos中获取assignBy

我的功能:

// get todos collection docid when oncreate happens in todoscomments collection
exports.insert_Notifi_ontrig_todoscomments = functions.firestore
.document('todoscomments/{todoscommentsId}')
.onCreate(
    async (snapshot: { data: () => { (): any; new(): any; message: any; taskid: any; from: any; fromName: any; }; },context:any) => {

      // todos details.
      const text = snapshot.data();
      const taskid = text.taskid; // this is docid of todos collection


                  //get data of todos doc
                    const query3 = admin.firestore().collection('todos').doc(taskid)
                    await query3.get()
                    .then(function(querySnapshot: any[]) {
                      querySnapshot.forEach(doc=> {
                          const assignBy = doc.data().assignBy;
                          console.log(assignBy);
                      });
                  })

                          .catch(function(error: any) {
                              console.log("Error getting documents: ", error);
                          });


    });

我想获取 assignBy 的值,附上 todos 的截图

在此处输入图像描述

标签: javascriptfirebasegoogle-cloud-firestoregoogle-cloud-functions

解决方案


此查询根本不是 Query 对象:

const query3 = admin.firestore().collection('todos').doc(taskid)

query3是一个DocumentReference类型的对象,它引用单个文档。当你get()这样做时,它会返回一个承诺,该承诺会产生一个带有单个文档(而不是 QuerySnapshot)的 DocumentSnapshot 正如您从 API 文档中看到的,它没有 forEach 方法,因为结果中只有 0 或 1 个文档。如果你想要那个文件,你应该首先检查它是否存在,直接调用data()就可以了。


推荐阅读