Mongoose complex (async) virtuals

2019-01-12 04:13发布

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!

1条回答
地球回转人心会变
2楼-- · 2019-01-12 04:41

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);
});
查看更多
登录 后发表回答