Mongoose 复杂(异步)虚拟 [英] Mongoose complex (async) virtuals
本文介绍了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 时,我也会得到虚拟生成的小队:
When I query Teams I would to get also the virtual generated squad:
Teams.find({}, function(err, teams) {
JSON.stringify(teams); /* => [{
name: 'team-1',
squad: [{ name: 'player-1' } , ...]
}, ...] */
});
但我不能获得这个使用虚拟,因为我需要一个异步调用:
but I can't get this using virtuals, because I need an async call:
teamSchema.virtual('squad').get(function() {
Players.find({ team_id: this._id }, function(err, players) {
return players;
});
}); // => undefined
实现这一结果的最佳方法是什么?
What is the best way to achieve this result?
谢谢!
推荐答案
这可能最好作为 实例方法添加到teamSchema
,以便调用者可以提供回调以接收异步结果:
This is probably best handled as an instance method you add to teamSchema
so that the caller can provide a callback to receive the async result:
teamSchema.methods.getSquad = function(callback) {
Players.find({ team_id: this._id }, callback);
});
这篇关于Mongoose 复杂(异步)虚拟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文