0

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

var Question = new Schema({
  title: {type: String},
  answers: Schema.Types.Mixed, //{A:'',B:''}
  category: {type: String}, 
  type: {type: String},        
  enable: {type: Boolean, default: true},
  sex: Number,             
  //random: {type: Number, default: Math.random}, 
  createdAt: {type: Date, default: Date.now} 
});

var User = new Schema({
  username: {type: String},    
  password: {type: String},
  typeQuestion: [{q: {type: Schema.Types.ObjectId, ref: 'Question'}, a: String,option:String }],    
});

How to populate typeQuestion from User, Anyone can tell me how to do it?

Holly
  • 13
  • 2
  • 6

1 Answers1

3

Very simple:

User.find({})
    .populate('typeQuestion.q')
    .exec(function(err, user) {
        // callback
    });

You can populate items in an array by simply referring to this item and "ignoring" the array.

Thomas Bormans
  • 5,156
  • 6
  • 34
  • 51