同时填充多个字段

时间:2015-01-28 01:37:26

标签: node.js mongodb mongoose

我有一个名为Chat的模式:

var ChatSchema   = new Schema({
    vehicle: { type: Schema.Types.ObjectId, ref: 'Vehicle' },
    messages: [String]
});

...和另一个名为Vehicle的模式:

var VehicleSchema   = new Schema({
    make: { type: Schema.Types.ObjectId, ref: 'Make' },
    model: { type: Schema.Types.ObjectId, ref: 'Model' }
});

我需要一个填充车辆的查询,但也需要#34; make"和"模型"车内的字段。我试过这个但是无法使它发挥作用。尝试过路径但没有成功。

Chat.find(function (err, chats) {
    if (err)
         res.json({ success: false, response: err });

    if (chats.length == 0)
         res.json({ success: false, response: "Nothing found." });
    else
         res.json({ success: true, response: { chats: chats } });
}).populate('vehicle make model');

1 个答案:

答案 0 :(得分:1)

嵌套人口必须在单独的步骤中完成,这使得它有点尴尬,但你可以使用这样的方法来实现:

Chat.find().populate('vehicle').exec(function (err, chats) {
    Make.populate(chats, 'vehicle.make', function (err, chats) {
        ModelModel.populate(chats, 'vehicle.model', function (err, chats) {
            if (err)
                 res.json({ success: false, response: err });

            if (chats.length == 0)
                 res.json({ success: false, response: "Nothing found." });
            else
                 res.json({ success: true, response: { chats: chats } });
        });
    });
});

文档here