2

With mongoose, I want to populate a property inside a subdocument of my main document. Here is my models:

var device = {
    deviceId: {type: String, required: true},
    number: {type: Number, default: 0}
};

var notification = new Schema({
   createdAt: {type: Date, default: Date.now},
   device: {type: Schema.ObjectId, ref: 'Device'}
});

var clientSchema = new Schema({
    [...]
    information: {
        code: {type: String, required: true},
        name: {type: String, required: true}
    },
    notifications: [notification],
    [...]
});

What I'm trying to do it's to get notifications with the device populated.

I tried this:

 clientModel.findOne({"information.code": id})
      .populate('notifications')
      .populate('notifications.device')
      .exec(function(err, client) {
          if (err) {
              console.log(err);
              next(err, null);
          }
          if (client) {
              console.log(client.notifications);
              next(null, client.notifications);
          }
      });

And I got this

[{ device: 55634975d20f1f3903ff4325,
   _id: 5564b1139ac484db0251b4a2,
   createdAt: Tue May 26 2015 19:44:51 GMT+0200 (CEST) }]

Anyone can tell me what I'm doing wrong please ?? Thanks for your help guys :)

Pat
  • 329
  • 1
  • 3
  • 11
  • possible duplicate of [Mongoose: deep population (populate a populated field)](http://stackoverflow.com/questions/18867628/mongoose-deep-population-populate-a-populated-field) – laggingreflex May 28 '15 at 03:05

2 Answers2

0

In your clientSchema notifications is an embed so you do not need to populate it. Try to remove the populate('notifications') in your query. You should just need the populate('notifications.device').

Julien Bachmann
  • 753
  • 8
  • 18
0

The correct way to populate is:

clientModel.findOne({"information.code": id})
      .populate('notifications.device')
      .exec(function(err, client) {
          if (err) {
              console.log(err);
              next(err, null);
          }
          if (client) {
              console.log(client.notifications);
              next(null, client.notifications);
          }
      });

Note that the use of .populate('notifications') is unnecessary because notification is not referenced but embedded. This line could be causing the problem.

Arthur Silva
  • 878
  • 1
  • 10
  • 15