猫鼬复杂(异步)虚函数(Mongoose complex (async) virtuals)

2019-07-19 21:13发布

我有两个猫鼬架构如下:

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

什么是实现这一结果的最佳方式?

谢谢!

Answer 1:

这可能是最好的,因为一个处理实例方法您添加到teamSchema ,使主叫方可以提供一个回调来接收异步的结果:

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


文章来源: Mongoose complex (async) virtuals