Populating array of ObjectId's in Mongoose 3.8

458 Views Asked by At

I'm trying populate an array with entire information of another collection and I can't get it.

I have 2 collections: users and exams and I want to show a json response containing user information and exams buyed by the user.

My problem is that I don't know how to populate examsPurchased with entired exams information (name,numberOfQuestions,yearOfExam...) ¿How can I do that?

This is my final result

enter image description here

And this is my code

// USER MODEL

var mongoose     = require('mongoose');
var Schema       = mongoose.Schema;

// Schemas

var userSchema   = new Schema({
    name : String,
    hobbies: {
        name : String,
        ubicacion:String
    },
    examsPurchased : [new Schema({
        exams: {type: Schema.ObjectId, ref: 'exams'}
    })]
});

module.exports = mongoose.model('users', userSchema);

// EXAM MODEL

var mongoose     = require('mongoose');
var Schema       = mongoose.Schema;

// Schemas
var examSchema   = new Schema({
    year        : Number,
    count       : Number
});

module.exports = mongoose.model('exams', examSchema);

// ROUTES
router.route('/user/:user_id').get(function(req,res){
    user
    .findById(req.params.user_id)
    .populate('examsPurchased._id')
    .exec(function (err, completeUser) {
      if(err) {
        console.log(err);
      }
      res.send(completeUser);
    });
});
1

There are 1 best solutions below

6
On BEST ANSWER

The problem is that you aren't populating the good field:

// ROUTES
router.route('/user/:user_id').get(function(req,res){
    user
    .findById(req.params.user_id)
    .populate('examsPurchased.exams', 'year count') // Line changed
    .exec(function (err, completeUser) {
      if(err) {
        console.log(err);
      }
      res.send(completeUser);
    });
});