如何在Cloud Firestore查询中加入多个文档? [英] How to join multiple documents in a Cloud Firestore query?

查看:90
本文介绍了如何在Cloud Firestore查询中加入多个文档?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个具有以下结构的Cloud Firestore数据库:

I have a Cloud Firestore DB with the following structure:


  • 用户


    • [uid]


      • 名称:测试用户


      • [id]


        • 内容:只是一些测试帖。

        • 时间戳:( 2017年12月22日)

        • uid:[ uid]

        那里实际数据库中存在更多数据,上面只是说明了集合/文档/字段结构。

        There is more data present in the actual DB, the above just illustrates the collection/document/field structure.

        我在我的网络应用程序中有一个视图,我在哪里显示帖子并希望显示发布的用户的名称。我正在使用以下查询来获取帖子:

        I have a view in my web app where I'm displaying posts and would like to display the name of the user who posted. I'm using the below query to fetch the posts:

        let loadedPosts = {};
        posts = db.collection('posts')
                  .orderBy('timestamp', 'desc')
                  .limit(3);
        posts.get()
        .then((docSnaps) => {
          const postDocs = docSnaps.docs;
          for (let i in postDocs) {
            loadedPosts[postDocs[i].id] = postDocs[i].data();
          }
        });
        
        // Render loadedPosts later
        

        我想要做的是查询存储在post的uid字段中的uid的用户对象,并将用户的name字段添加到相应的loadedPosts对象中。如果我一次只加载一个帖子就没问题,只需等待查询返回一个对象,然后在 .then()函数中再创建一个查询用户文档,等等。

        What I want to do is query the user object by the uid stored in the post's uid field, and add the user's name field into the corresponding loadedPosts object. If I was only loading one post at a time this would be no problem, just wait for the query to come back with an object and in the .then() function make another query to the user document, and so on.

        但是因为我一次收到多个帖子文件,所以我很难搞清楚如何映射在每个帖子的用户/ [uid] 文件上调用 .get()后,将用户更正为正确的帖子他们回归的异步方式。

        However because I'm getting multiple post documents at once, I'm having a hard time figuring out how to map the correct user to the correct post after calling .get() on each post's user/[uid] document due to the asynchronous way they return.

        有人能想到这个问题的优雅解决方案吗?

        Can anyone think of an elegant solution to this issue?

        推荐答案

        我会做1个用户doc调用和所需的帖子调用。

        I would do 1 user doc call and the needed posts call.

        let users = {} ;
        let loadedPosts = {};
        db.collection('users').get().then((results) => {
          results.forEach((doc) => {
            users[doc.id] = doc.data();
          });
          posts = db.collection('posts').orderBy('timestamp', 'desc').limit(3);
          posts.get().then((docSnaps) => {
            docSnaps.forEach((doc) => {
            loadedPosts[doc.id] = doc.data();
            loadedPosts[doc.id].userName = users[doc.data().uid].name;
          });
        }); 
        

        这篇关于如何在Cloud Firestore查询中加入多个文档?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆