Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose complex (async) virtuals

I have two mongoose schemas as follow:

var playerSchema = new mongoose.Schema({
    name: String,
    team_id: mongoose.Schema.Types.ObjectId
});
Players = mongoose.model('Players', playerSchema);

var teamSchema = new mongoose.Schema({
    name: String
});
Teams = mongoose.model('Teams', teamSchema);

When I query Teams I would to get also the virtual generated squad:

Teams.find({}, function(err, teams) {
  JSON.stringify(teams); /* => [{
      name: 'team-1',
      squad: [{ name: 'player-1' } , ...]
    }, ...] */
});

but I can't get this using virtuals, because I need an async call:

teamSchema.virtual('squad').get(function() {
  Players.find({ team_id: this._id }, function(err, players) {
    return players;
  });
}); // => undefined

What is the best way to achieve this result?

Thanks!

like image 512
frx08 Avatar asked Feb 14 '13 14:02

frx08


1 Answers

This is probably best handled as an instance method you add to teamSchema so that the caller can provide a callback to receive the async result:

teamSchema.methods.getSquad = function(callback) {
  Players.find({ team_id: this._id }, callback);
});
like image 197
JohnnyHK Avatar answered Oct 24 '22 04:10

JohnnyHK