【问题标题】:Populating nested properties with Mongoose使用 Mongoose 填充嵌套属性
【发布时间】:2014-10-27 09:57:52
【问题描述】:

在我尝试使用 Node 和 Mongoose 编写的 API 中,以下查询:

User.findOne({username: req.params.username}, "-_id -__v")
    .populate({path: "songs", select: "-_id -__v"})
    .populate({path: "following", select: "-_id username email"})
    .exec(function(err, user) {
        res.send(user);
    });

返回以下 JSON:

{
    "email": "alice@alice.org",
    "username": "alice",
    "following": [
        {
        "username": "john",
        "email": "john@john.org"
        }
    ],
    "songs": [
        {
            "slug": "dvorak-cello-concerto",
            "artist": "5403e825cc9c45e9c55c4e7d",
            "title": "Cello Concerto"
        }
    ]
}

在歌曲架构中,我将艺术家设置如下:

artist: {type: Schema.Types.ObjectId, ref: 'User'}

在初始查询中填充的每首歌曲中填充“艺术家”属性的最佳方法是什么,而不仅仅是引用该歌曲所属用户的 _id?

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    我想出了一种方法来做到这一点,但如果有更好/更清洁的方法,请纠正我。

    User.findOne({username: req.params.username}, "-_id -__v")
        .populate({path: "songs", select: "-_id -__v"})
        .exec(function(err, user) {
            Songs.populate(user, {
                path: 'songs.artist',
                select: '-_id username',
                model: 'User'
            }, function (err, user) {
                res.send(user);
            });
        });
    

    另外,我只返回用户的“用户名”值,这是我所需要的,但“艺术家”最终仍然是具有该属性的对象。如果有人知道如何将该值作为字符串返回。

    我很想知道怎么做。

    【讨论】:

      猜你喜欢
      • 2018-06-07
      • 1970-01-01
      • 2017-10-03
      • 2015-03-26
      • 1970-01-01
      • 1970-01-01
      • 2020-06-07
      • 2019-12-06
      相关资源
      最近更新 更多