0

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);
    });
});
dpbataller
  • 1,197
  • 4
  • 12
  • 23

1 Answers1

0

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);
    });
});
Vinz243
  • 9,654
  • 10
  • 42
  • 86
  • I've changed .populate('examsPurchased.exams') but it doesn't works :( I don't understand the problem – dpbataller Jun 03 '14 at 18:10
  • Sorry, the result is the same as before even changing .populate('examsPurchased.exams') What can I check? – dpbataller Jun 03 '14 at 19:53
  • I don't understand. Your result is the image? This isn't console.log, is it? – Vinz243 Jun 04 '14 at 12:03
  • Yes, my result is the image, not a console.log(). I've change the line suggested by you .populate('examsPurchased.exams'), and the result is the same as the original image, still not working – dpbataller Jun 04 '14 at 12:48
  • How did you get this image? – Vinz243 Jun 04 '14 at 13:32
  • With an a Chrome extension called Postman. This image is the result of a get request to /user/:user_id and the JSON response it's the image that you're viewing. My problem is that I need to populate examsPurchased filed with the exams info located in a collection called exams. But I can't do it – dpbataller Jun 04 '14 at 13:45