mongoose复杂(asynchronous)虚拟

我有两个mongoose模式如下:

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

当我查询队伍时,我也会得到虚拟生成的队伍

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

但我不能 使用虚拟 ,因为我需要一个asynchronous调用:

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

达到这个结果的最好方法是什么?

谢谢!

这可能是最好的处理方式,你添加到teamSchema的实例方法 ,以便调用者可以提供callback来接收asynchronous结果:

 teamSchema.methods.getSquad = function(callback) { Players.find({ team_id: this._id }, callback); }); 
    Interesting Posts