同时填充多个字段

Populate multiple fields at same time

我有一个名为 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' }
});

我需要一个查询来填充车辆以及车辆内部的 "make" 和 "model" 字段。我试过了,但没能成功。也尝试过路径但没有成功。

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');

嵌套填充必须在单独的步骤中完成,这使得它有点尴尬,但您可以使用这样的方法来完成:

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.