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

Categories

0 votes
450 views
in Technique[技术] by (71.8m points)

node.js - 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!

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...