来自父集合的空querySnapshot

时间:2020-04-27 23:55:20

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

有人知道父集合的文档中是否有迭代的方法吗? 我试图从父集合中获取每个文档,但是querySnapshot似乎是空的,而事实并非如此。

My function log that show a querySnapshot of size equal to 0

Here my firestore collections

我的收藏路径如下:

parentCollection(comments)/docs/subCollection(comments)/docs

我想做的是在每个子集合及其文档中进行迭代,为此,我需要在父集合的每个文档中进行迭代,但是当我使用get()时,它将返回一个空的querySnapshot。 >

这是我的代码:

return admin.firestore().collection("comments").get().then((querySnapshot) => {
    console.log(querySnapshot);
    querySnapshot.forEach((doc) => {
      console.log(doc);
      return doc.ref.collection("comments").get().then((querySnapshot2) => {
        console.log(querySnapshot2);
        querySnapshot2.forEach((doc2) => {
          console.log(doc2.data());
        })
        return true;
      });
    });
    return true;
  });

Ps:我知道,我不应该嵌套诺言。

更新

这是我的console.log在日志querySnapshot.sizequerySnapshot.empty时返回的内容:

console.log of my querySnapshot.size & querySnapshot.empty

这里是整个代码:

const functions = require("firebase-functions");
const admin = require("firebase-admin");
admin.initializeApp();


exports.onUpdateUserUpdateComments = functions.firestore
    .document("/users/{userId}")
    .onUpdate(async (change, context) => {
      const userId = context.params.userId;
      const userUpdate = change.after.data();
      const newPhotoUrl = userUpdate.photoUrl;
      console.log("userId",userId);
      console.log("newPhotoUrl",newPhotoUrl);
      return admin.firestore().collection("comments").get().then((querySnapshot) => {
        console.log(querySnapshot.size);
        console.log(querySnapshot.empty);
        querySnapshot.forEach((doc) => {
          console.log(doc);
          return doc.ref.collection("comments").get().then((querySnapshot2) => {
            console.log(querySnapshot2);
            querySnapshot2.forEach((doc2) => {
              console.log(doc2.data());
            })
            return true;
          });
        });
        return true;
      });
 });

在此处部署日志输出后

enter image description here

2 个答案:

答案 0 :(得分:0)

我已经实现了此功能,它完全可以复制/粘贴您的代码,并且可以确认它可以正常工作。

我当然也为测试Firestore添加了结构:

-comments - <genrated docID1> -comments - empty
          - <genrated docID2> -comments - <dummy document> 

还有users结构也可以使触发器起作用。我通过手动更新“ photoUrl”字段来触发它。

querySnapshot.size的结构为2,而querySnapshot.emptyfalse

实际上,您可能在日志QuerySnapshot中带有_size: 0,的日志,但这是针对此嵌套的空“ comments”集合的。

此代码父集合QuerySnapshot中的

BTW根本没有记录。仅父集合和嵌套集合的文档。

我希望这会有所帮助!

答案 1 :(得分:0)

经过多次测试后,我可以看到问题是由于以下事实造成的:即使从控制台可见文档,它们也不存在。 它们不存在,因为即使它们包含子集合,也不会被视为数据。因此,这就是该文档用斜体显示的原因,以及为什么显示下一个句子的原因:“ 该文档不存在,并且不会出现在查询或快照中

要解决此问题,您必须将数据添加到这些文档中,然后在不需要时将其删除,或者可以在控制台中手动创建它们。 甚至更好的是,如果不想更改代码中的任何内容,则可以使用 listDocuments 方法。 Admin SDK提供了一个具有以下说明的 listDocuments 方法:

返回的文档引用可能包括对“缺少文档”的引用,即不存在文档但包含文档子集合的文档位置。尝试读取此类文档引用(例如,通过.get()或.onSnapshot())将返回其.exists属性为false的DocumentSnapshot。