Node.js Mongoose复杂(异步)虚拟
我有两个猫鼬模式,如下所示:Node.js Mongoose复杂(异步)虚拟,node.js,mongodb,asynchronous,mongoose,virtual,Node.js,Mongodb,Asynchronous,Mongoose,Virtual,我有两个猫鼬模式,如下所示: 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
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
实现这一结果的最佳方式是什么
谢谢 这可能是您添加到
teamSchema
的最佳处理方式,以便调用者可以提供回调以接收异步结果:
teamSchema.methods.getSquad = function(callback) {
Players.find({ team_id: this._id }, callback);
});
但是,例如,在CRUD服务中,当我想要获得团队的团队列表时,我必须找到团队。查找->循环每个团队->为每个团队获取团队->创建团队数组的克隆(因为我无法在返回的数组中注入新属性),然后为每个团队注入团队->res.json(clonedArray)?当您需要像这里一样操纵查询结果时,请在查询中使用
teams.find().lean().exec(cb)
今天有更好的解决方案吗?今天呢?3年后,根据猫鼬的说法,填充插件可能是一种选择