我有两个 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' } , ...]
}, ...] */
});
但我无法使用虚拟获取此,因为我需要异步调用:
teamSchema.virtual('squad').get(function() {
Players.find({ team_id: this._id }, function(err, players) {
return players;
});
}); // => undefined
实现这一结果的最佳方法是什么?
谢谢!
答案 0 :(得分:4)
这可能最好作为instance method添加到teamSchema
处理,以便调用者可以提供回调来接收异步结果:
teamSchema.methods.getSquad = function(callback) {
Players.find({ team_id: this._id }, callback);
});