【问题标题】:how to get find another model values from another model?如何从另一个模型中找到另一个模型值?
【发布时间】:2020-06-15 20:50:18
【问题描述】:

我想查找用户模型值并希望将该值存储在我当前的博客模型中

exports.getAllBlogs = async (req, res) => {
  try {
    const blogs = await Blog.find()
      .sort({ created_at: -1 })
      .populate({
        path: "comments"
      })
      .exec();
    const myblogs = blogs.map(async blog => {
      const user = await User.findOne({ _id: blog.author });
      return (blog.authorName = user.name);
    });
    console.log(myblogs);

    if (blogs.length === 0) {
      return res.status(404).json({ message: "No Blogs Found" });
    }

    return res.status(200).json(myblogs);
  } catch (error) {
    console.log(error);

    res.status(500).json({ error: "Something went wrong" });
  }
};

但这是回报我 [ Promise { } ] 对于每个集合

我怎样才能做到这一点,或者有没有更好的方法来做到这一点?

【问题讨论】:

    标签: javascript node.js mongodb mongoose nosql


    【解决方案1】:

    您无需地图即可通过填充获取所有相关信息。

    exports.getAllBlogs = async (req, res) => {
      try {
        const blogs = await Blog.find({})
          .sort({ created_at: -1 })
          .populate("author", "-password")
          .populate({
            path: "comments",
            populate: {
              path: "user",
              select: "-password"
            }
          });
    
        return res.status(200).json(blogs);
      } catch (error) {
        console.log(error);
        res.status(500).json({ error: "Something went wrong" });
      }
    };
    

    这将给出如下示例结果:

    [
        {
            "_id": "5e53b2896f41c765fc4defa1",
            "title": "Blog2 Title",
            "body": "Blog2 Body",
            "author": {
                "_id": "5e53b1726f41c765fc4def9c",
                "email": "user1@gmail.com",
                "name": "User1",
                "created_at": "2020-02-24T11:20:18.343Z",
                "updated_at": "2020-02-24T11:20:18.343Z",
                "id": "5e53b1726f41c765fc4def9c"
            },
            "created_at": "2020-02-24T11:24:57.078Z",
            "updated_at": "2020-02-24T11:24:57.078Z",
            "__v": 0,
            "comments": [
                {
                    "_id": "5e53b34c6f41c765fc4defa5",
                    "body": "Comment3 (user2 on user1's blog2)",
                    "user": {
                        "_id": "5e53b1906f41c765fc4def9d",
                        "email": "user2@gmail.com",
                        "name": "User2",
                        "created_at": "2020-02-24T11:20:48.070Z",
                        "updated_at": "2020-02-24T11:20:48.070Z",
                        "__v": 0,
                        "id": "5e53b1906f41c765fc4def9d"
                    },
                    "blog": "5e53b2896f41c765fc4defa1",
                    "created_at": "2020-02-24T11:28:12.551Z",
                    "updated_at": "2020-02-24T11:28:12.551Z"
                }
            ],
            "id": "5e53b2896f41c765fc4defa1"
        },
        {
            "_id": "5e53b26c6f41c765fc4def9f",
            "title": "Blog1 Title",
            "body": "Blog1 Body",
            "author": {
                "_id": "5e53b1726f41c765fc4def9c",
                "email": "user1@gmail.com",
                "name": "User1",
                "created_at": "2020-02-24T11:20:18.343Z",
                "updated_at": "2020-02-24T11:20:18.343Z",
                "id": "5e53b1726f41c765fc4def9c"
            },
            "created_at": "2020-02-24T11:24:28.895Z",
            "updated_at": "2020-02-24T11:24:28.895Z",
            "__v": 0,
            "comments": [
                {
                    "_id": "5e53b2f86f41c765fc4defa3",
                    "body": "Comment1 (user2 on user1's blog1)",
                    "user": {
                        "_id": "5e53b1906f41c765fc4def9d",
                        "email": "user2@gmail.com",
                        "name": "User2",
                        "created_at": "2020-02-24T11:20:48.070Z",
                        "updated_at": "2020-02-24T11:20:48.070Z",
                        "id": "5e53b1906f41c765fc4def9d"
                    },
                    "blog": "5e53b26c6f41c765fc4def9f",
                    "created_at": "2020-02-24T11:26:48.506Z",
                    "updated_at": "2020-02-24T11:26:48.506Z"
                },
                {
                    "_id": "5e53b3246f41c765fc4defa4",
                    "body": "Comment2 (user3 on user1's blog1)",
                    "user": {
                        "_id": "5e53b1996f41c765fc4def9e",
                        "email": "user3@gmail.com",
                        "name": "User3",
                        "created_at": "2020-02-24T11:20:57.488Z",
                        "updated_at": "2020-02-24T11:20:57.488Z",
                        "id": "5e53b1996f41c765fc4def9e"
                    },
                    "blog": "5e53b26c6f41c765fc4def9f",
                    "created_at": "2020-02-24T11:27:32.305Z",
                    "updated_at": "2020-02-24T11:27:32.305Z"
                }
            ],
            "id": "5e53b26c6f41c765fc4def9f"
        }
    ]
    

    【讨论】:

      【解决方案2】:

      因为您在地图中使用异步。这将返回 Promises 数组。

      试试这个

      const myblogs = await Promise.all(
        blogs.map(async blog => {
            const user = await User.findOne({ _id: blog.author });
            blog.authorName = user.name;
            return blog;
         })
      );

      【讨论】:

      • 这行得通,但现在我只得到名字,然后我更改了一些代码` const myblogs = await Promise.all( blogs.map(async blog => { const user = await User.findOne({ _id : blog.author }); blog.author = user.name; return blog; }) );` 但它没有返回它返回相同值的值有没有更好的方法来实现这一点,比如查询或可以得到每个博客作者姓名和 ID?
      • blog.authorName = user.nameblog.author = user.name; return blog; 不同。可能是错误?你需要blog.**authorName** = user.name; return blog;
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-13
      • 2013-10-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多