猫鼬复杂(异步)虚函数 [英] Mongoose complex (async) virtuals
本文介绍了猫鼬复杂(异步)虚函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有两个猫鼬架构如下:
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);
当我询问我的团队也将获得虚拟生成的阵容
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);
});
这篇关于猫鼬复杂(异步)虚函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文