2015-05-26 2 views
2

С мангустом, я хочу заполнить свойство внутри поддокумента моего основного документа. Вот мои модели:Mongoose + Заполнить свойство в поддокументе

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], 
    [...] 
}); 

То, что я пытаюсь сделать это, чтобы получать уведомления с устройством заселенным.

Я попытался это:

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

И я получил это

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

Любой человек может сказать мне, что я делаю неправильно, пожалуйста ?? Спасибо за помощь, ребята :)

+0

Возможный дубликат [Mongoose: глубокая популяция (заполнение населенного поля)] (http://stackoverflow.com/questions/18867628/mongoose-deep-population-populate-a-populated-field) – laggingreflex

ответ

0

В ваших уведомлениях clientSchema встроен, поэтому вам не нужно его заполнять. Попробуйте удалить заполнение («уведомления») в запросе. Вам просто нужно заполнить («notifications.device»).

0

Правильный способ для заполнения является:

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

Обратите внимание, что использование .populate («уведомление») ненужно, потому что уведомления является нессылкой но встроенного. Эта строка может вызвать проблему.

 Смежные вопросы

  • Нет связанных вопросов^_^