CainaSouza
CainaSouza

Reputation: 1437

Populate multiple fields at same time

I have a schema called Chat:

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

...and another schema called Vehicle:

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

I need a query that populates the vehicle but also "make" and "model" fields that are inside vehicle. I tried this but couldn't make it work. Tried with paths too but no success.

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

Upvotes: 1

Views: 100

Answers (1)

JohnnyHK
JohnnyHK

Reputation: 312045

Nested population must be done in separate steps which makes it a bit awkward, but you can do it using an approach like this:

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

Docs here.

Upvotes: 1

Related Questions