问题填充 Mongoose 模型

l7wslrjt  于 12个月前  发布在  Go
关注(0)|答案(1)|浏览(160)

我有两个模型,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。

ve7v8dk2

ve7v8dk21#

要使Model.poplate工作,您需要根据docs引用_id字段。进行以下更改:

var PokemonSchema = new Schema({
  name: {
    type: String,
    required: true
  //..
  //..
  moves: [{
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Attack'
  }]
});

字符串
您需要手动添加您想要在Pokemon中引用的每个AttackAttack._id。这不会自动发生。findByIdAndUpdatefindOneAndUpdate等方法将帮助您完成此操作。
当你搜索时:

try{
   const docs = await Pokemon.find({}).populate({path: "moves"});
}catch(err){
   console.log(err);
}

相关问题