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

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

问题描述

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

I have a Cloud Firestore DB with the following structure:

  • 用户
    • [用户名]
      • 姓名:测试用户"
      • [id]
        • 内容:只是一些测试帖子."
        • 时间戳:(2017 年 12 月 22 日)
        • uid:[uid]

        实际DB中存在更多数据,以上只是说明了集合/文档/字段结构.

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

        我的 Web 应用中有一个视图,我在其中显示帖子,并希望显示发布用户的姓名.我正在使用以下查询来获取帖子:

        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查询user对象,并将用户的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.

        但是,因为我一次收到多个帖子文档,所以在每个帖子上调用 .get() 后,我很难弄清楚如何将正确的用户映射到正确的帖子user/[uid] 文档由于它们返回的异步方式.

        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 个用户文档调用和需要的帖子调用.

        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天全站免登陆