问题填充 Mongoose 模型

l7wslrjt  于 2024-01-08  发布在  Go
关注(0)|答案(1)|浏览(222)

我有两个模型,Pokemon和Attacks。Pokemon模型有一个作为字符串的移动数组,我想用Attack名称作为键填充Attacks集合。

口袋妖怪模型

  1. var mongoose = require("mongoose");
  2. var Schema = mongoose.Schema;
  3. var PokemonSchema = new Schema({
  4. name: {
  5. type: String,
  6. required: true
  7. },
  8. types: [{
  9. type: String,
  10. required: true
  11. }],
  12. abilities: [{
  13. type: String,
  14. required: true
  15. }],
  16. stats: [{
  17. type: Number,
  18. required: true
  19. }],
  20. moves: [{
  21. type: String,
  22. ref: 'Attack'
  23. }]
  24. });
  25. var Pokemon = mongoose.model("Pokemon", PokemonSchema);
  26. module.exports = Pokemon;

字符串

攻击模型

  1. var mongoose = require("mongoose");
  2. var Schema = mongoose.Schema;
  3. var AttackSchema = new Schema({
  4. name: {
  5. type: String,
  6. required: true
  7. },
  8. power: {
  9. type: Number,
  10. required: true
  11. },
  12. accuracy: {
  13. type: Number,
  14. required: true
  15. },
  16. type: {
  17. type: String,
  18. required: true
  19. },
  20. damage_class: {
  21. type: String,
  22. required: true
  23. },
  24. target: {
  25. type: String,
  26. required: true
  27. }
  28. });
  29. var Attack = mongoose.model("Attack", AttackSchema);
  30. module.exports = Attack;

填写编码

  1. await Pokemon.find({}).populate({path: "moves"}).then((err, docs) => {
  2. if (err){
  3. console.log(err);
  4. }
  5. console.log(docs[0].moves[0].power)
  6. })


运行这个给了我一个错误,以至于控制台似乎无法记录整个事情。问题是口袋妖怪模型中的moves属性不是object_id吗?我用来获取这些数据的API只给了我攻击的名称,而不是它们各自的id。

ve7v8dk2

ve7v8dk21#

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

  1. var PokemonSchema = new Schema({
  2. name: {
  3. type: String,
  4. required: true
  5. //..
  6. //..
  7. moves: [{
  8. type: mongoose.Schema.Types.ObjectId,
  9. ref: 'Attack'
  10. }]
  11. });

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

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

展开查看全部

相关问题