我有两种 猫鼬模式 ,如下所示:
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' } , ...] }, ...] */ });
但是我 无法 使用virtuals 来 获得它,因为我需要一个 异步 调用:
teamSchema.virtual('squad').get(function() { Players.find({ team_id: this._id }, function(err, players) { return players; }); }); // => undefined
实现此结果的最佳方法是什么?
谢谢!
这可能最好作为您添加到的实例方法来处理,teamSchema以便调用者可以提供回调以接收异步结果:
teamSchema
teamSchema.methods.getSquad = function(callback) { Players.find({ team_id: this._id }, callback); });