我有两个模型,Pokemon和Attacks。Pokemon模型有一个作为字符串的移动数组,我想用Attack名称作为键填充Attacks集合。
口袋妖怪模型
var mongoose = require("mongoose");
var Schema = mongoose.Schema;
var PokemonSchema = new Schema({
name: {
type: String,
required: true
},
types: [{
type: String,
required: true
}],
abilities: [{
type: String,
required: true
}],
stats: [{
type: Number,
required: true
}],
moves: [{
type: String,
ref: 'Attack'
}]
});
var Pokemon = mongoose.model("Pokemon", PokemonSchema);
module.exports = Pokemon;
字符串
攻击模型
var mongoose = require("mongoose");
var Schema = mongoose.Schema;
var AttackSchema = new Schema({
name: {
type: String,
required: true
},
power: {
type: Number,
required: true
},
accuracy: {
type: Number,
required: true
},
type: {
type: String,
required: true
},
damage_class: {
type: String,
required: true
},
target: {
type: String,
required: true
}
});
var Attack = mongoose.model("Attack", AttackSchema);
module.exports = Attack;
型
填写编码
await Pokemon.find({}).populate({path: "moves"}).then((err, docs) => {
if (err){
console.log(err);
}
console.log(docs[0].moves[0].power)
})
型
运行这个给了我一个错误,以至于控制台似乎无法记录整个事情。问题是口袋妖怪模型中的moves属性不是object_id吗?我用来获取这些数据的API只给了我攻击的名称,而不是它们各自的id。
1条答案
按热度按时间ve7v8dk21#
要使
Model.poplate
工作,您需要根据docs引用_id
字段。进行以下更改:字符串
您需要手动添加您想要在
Pokemon
中引用的每个Attack
的Attack._id
。这不会自动发生。findByIdAndUpdate
或findOneAndUpdate
等方法将帮助您完成此操作。当你搜索时:
型