gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 13:22:46 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/14877134/

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