gpt4 book ai didi

node.js - Mongoose 复杂(异步)虚拟

转载 作者:太空宇宙 更新时间:2023-11-04 02:30:05 25 4
gpt4 key购买 nike

我有两个 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 时,我还会获取虚拟生成的球队:

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

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

谢谢!

最佳答案

最好将其处理为 instance method您添加到 teamSchema 以便调用者可以提供回调来接收异步结果:

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

关于node.js - Mongoose 复杂(异步)虚拟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27552841/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com