为特定的字段填充嵌套在数组内的对象的一个​​路径

时间:2019-05-24 00:16:40

标签: mongodb mongoose

“我的帖子”架构有一个“评论”数组路径,对于每个“评论”,“用户”是用户模态的objectId。我该如何为用户仅填充“名称”,“ _ id”,“缩略图URI”。

帖子数据库的外观:

[
...
  {
        "_id": "5ce5b41222fa4937f8a495e5",
        "owner": "5ce5b41123456789f8a495e5",
        "uri": "uri.jpg",
        "comments": [
            {
                "date": "2019-05-23T23:24:47.554Z",
                "_id": "5ce72bbf88781b35fca696ce",
                "user": "5cdda3a4f5a8a077a9352f38",
                "content": "cute!!!"
            },
            {
                "date": "2019-05-23T23:28:52.941Z",
                "_id": "5ce72cb46fba6f1bece267db",
                "user": "5cdda3a4f5a8a077a9352f38",
                "content": "cute!!!"
            }
        ],
        "createAt": "2019-05-22T20:41:54.290Z",
        "__v": 0
    },
...
]

我希望“评论”如下所示:

"comments": [
            {
                "date": "2019-05-23T23:24:47.554Z",
                "_id": "5ce72bbf88781b35fca696ce",
                "user": {
                      "name": "name",
                      "_id": "5ce72cb46fb5ce72cb46fb"
                      "thumbnailURI": "thumbnailURI.jpg"
                 },
                "content": "cute!!!"
            },
            {
                "date": "2019-05-23T23:28:52.941Z",
                "_id": "5ce72cb46fba6f1bece267db",
                "user": {
                      "name": "name",
                      "_id": "5ce72cb46fb5ce72cb46fb"
                      "thumbnailURI": "thumbnailURI.jpg"
                 },
                "content": "cute!!!"
            }
        ],

尝试

posts
                .getByOwners(owners)
                .populate('owner', 'username thumbnail _id')
                .populate({
                    path: "comments",
                    populate: {
                        path: "user",
                        model: "user",
                    }
                });

获取空的“评论”数组 谢谢!

1 个答案:

答案 0 :(得分:0)

感谢您的建议。

  1. 我有一个带有某些路径的“用户”模型

  2. 没有“评论”模型。 “ comments”是嵌入在“ post”模型中的数组。

查询如下:

posts
.findById(id)
.populate('owner', 'username thumbnail _id')
.populate("comments.user", 'username thumbnail _id')

这是我想要的最终结果:

"comments": [
            {
                "date": "2019-05-23T23:24:47.554Z",
                "_id": "5ce72bbf88781b35fca696ce",
                "user": {
                    "thumbnail": "pic1.jpg",
                    "_id": "5cdda3a4f5a8a077a9352f38",
                    "username": "a"
                },
                "content": "cute!!!"
            },
            {
                "date": "2019-05-23T23:28:52.941Z",
                "_id": "5ce72cb46fba6f1bece267db",
                "user": {
                    "thumbnail": "pic2.jpg",
                    "_id": "5cdda3a4f5a8a077a9352f38",
                    "username": "a"
                },
                "content": "cute!!!"
            }
],