Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
435 views
Welcome To Ask or Share your Answers For Others

1 Answer

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);
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...