【问题标题】:Firestore how can i get top-level collection inside documents list?Firestore 如何在文档列表中获取顶级集合?
【发布时间】:2021-04-18 19:14:38
【问题描述】:

example1) 集合 - 文档 - 集合 - 文档 - 集合

example2) 集合

example1 结构,我可以导入最后一个集合内的所有文档列表。

example2 结构,我无法获取集合内的所有文档列表。

如何在文档列表中获取顶级集合?

这是我的代码。

// this is example1. this is working!!
  dbService
    .collection("users")
    .doc(uid)
    .collection(uid)
    .doc("video")
    .collection(uid)
    .onSnapshot((snapshot) => {
      snapshot.docs.map((doc, index) => {
        videoList.push(doc.data());
        console.log(doc.data());
      });
    });



// this is example2. this is not working !!!!!
  dbService
   .collection("users")
   .onSnapshot((snapshot) => {
    snapshot.docs.map((doc, index) => {
      videoList.push(doc.data());
      console.log(doc.data());
    });
  });

example2 是返回空数组。这是为什么?

【问题讨论】:

  • 乍一看,第二个 sn-p 对我来说很好。什么不起作用?所以:如果您在调试器中逐行执行代码,哪一行是第一行没有按照您的预期执行的操作?详细而具体地描述问题,因为这会增加有人提供帮助的机会。

标签: javascript firebase google-cloud-firestore


【解决方案1】:

从 Firestore 加载数据很浅。这意味着如果您从 users 集合加载文档,则不会自动包含来自子集合的数据。


如果您想从特定用户的video 子集合中加载数据,则需要进行额外调用:

  dbService
   .collection("users")
   .onSnapshot((snapshot) => {
    snapshot.docs.map((doc, index) => {
      if (/* this is a user you are interested in */) {
        snapshot.ref.collection(videos).get().then((videos) => {
          videos.forEach((video) => {
            videoList.push(video.data());
          })
          console.log(doc.data());
        });
      }
    });
  });

如果您想为所有用户加载所有视频,您可以使用所谓的集合组查询:

  dbService
   .collectionGroup("videos")
   .onSnapshot((snapshot) => {
    snapshot.docs.map((doc, index) => {
      videoList.push(doc.data());
      console.log(doc.data());
    });
  });

如果您想在此处查找特定视频的用户 ID,可以通过 doc.ref.parent.parent.id 找到它。

【讨论】:

  • 感谢您的回答!我想要的是加载顶部集合中的所有文档,是一样的吗?我按照你说的做了,但我没有得到正确的结果。
猜你喜欢
  • 2018-04-14
  • 2018-10-06
  • 1970-01-01
  • 1970-01-01
  • 2018-04-09
  • 2021-05-17
  • 2021-08-23
  • 2018-04-09
  • 2018-03-29
相关资源
最近更新 更多