7

我有两个猫鼬模式如下:

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 时,我还会获得虚拟生成的小队

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

实现此结果的最佳方法是什么?

谢谢!

4

1 回答 1

4

这可能最好作为您添加的实例方法teamSchema处理,以便调用者可以提供回调来接收异步结果:

teamSchema.methods.getSquad = function(callback) {
  Players.find({ team_id: this._id }, callback);
});
于 2013-02-14T15:16:19.927 回答