0

I have following models:

LeaderSchema = new app.mongoose.Schema({
    email: String,
    projects: [{ type: app.mongoose.Schema.ObjectId, ref: 'Project'}]
});

ProjectSchema = new app.mongoose.Schema({
    name: { type: String, required: true},
    leader: { type: app.mongoose.Schema.ObjectId, ref: 'Leader'}
});

Leader = app.mongoose.model('Leader', LeaderSchema);
Project = app.mongoose.model('Project', ProjectSchema);

What I want to do in my controller is to retrieve all projects with its respective leaders:

projects_controller.js:

module.exports = function(app) {
    app.ProjectsController = {
        index: function(req, res) {
            app.Project.find(function(err, projects) {
                res.send(projects)
            })
        }
    }
}

But this is giving as result the list of projects with only their leader's id

Is there a way to make mongoose eagerly fetch the leaders?

stites
  • 4,903
  • 5
  • 32
  • 43
Tomas Romero
  • 8,418
  • 11
  • 50
  • 72

1 Answers1

0

Although I would like a solution that defines the eager load behavior on the model, the solution I've found is using populate:

app.Project.find().populate('user').exec(function(err, projects) {
    res.send(projects)
})

Documentation for populate can be found here at mongoosejs.com.

stites
  • 4,903
  • 5
  • 32
  • 43
Tomas Romero
  • 8,418
  • 11
  • 50
  • 72