【问题标题】:Schema relationship returns undefined after populate模式关系在填充后返回未定义
【发布时间】:2019-09-17 11:19:17
【问题描述】:

在我的数据库中,我有两个集合,玩家和领域。我为它们创建了一个模式,它们相互引用。我查询玩家集合并尝试填充人口字段。然后我尝试控制台记录返回未定义的结果。

player.js(模型)

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const PlayerSchema = new Schema({
  name: {
    type: String,
    required: true
  },
  wins: {
    type: Number,
    required: true
  },
  losses: {
    type: Number,
    required: true
  },
  race: {
    type: String,
    required: true
  },
  realm: {
    type: Schema.Types.ObjectId,
    required: true,
    ref: 'Realm'
  }
});

module.exports = mongoose.model('Player', PlayerSchema, 'players');

realm.js(模型)

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const RealmSchema = new Schema({
  name: {
    type: String,
    required: true
  },
  population: [{
    type: Schema.Types.ObjectId, 
    ref: 'Player'
  }]
});

module.exports = mongoose.model('Realm', RealmSchema, 'realms');

player.js(控制器)

const Player = require('../models/player.js');
const Realm = require('../models/realm.js');

exports.getPlayers = (req, res) => {
  Player.find()
  .populate({
    path: 'realm',
    select: '_id name'
  })
  .then((players) => {
    console.log(players.realm);
    res.json(players);
  })
  .catch(err => {
    console.log(err);
  });
}

我期望的结果是这样的:

{
  "players": [
      {
        "name": "Grubby",
        "wins": 2397,
        "losses": 632,
        "race": "Orc",
        "realm": {
          "_id": "5ca1985ae03dd80007aa008f",
          "name": "EU"
        }
      }
  ]
}

【问题讨论】:

标签: node.js mongodb mongoose schema relationship


【解决方案1】:
exports.getPlayers = (req, res) => {
      Player.find().populate('realm').then((players) => {
        console.log(players.realm);
        res.json(players);
      })
      .catch(err => {
        console.log(err);
      });
    }

要使用填充,请在模型中定义参考变量并使用此语法在另一个表中使用。

更多详情请参考链接:

https://mongoosejs.com/docs/populate.html

【讨论】:

  • 感谢您的回复。我已经运行了你提供的代码,但我仍然收到未定义的。我在我的两个模型(领域和人口)中都设置了一个参考变量,它们看起来正确吗?我已完整阅读了 Mongoose 填充文档,但我似乎无法找到我的代码的问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-15
  • 1970-01-01
  • 2023-04-11
  • 1970-01-01
  • 2023-04-02
  • 2014-04-21
相关资源
最近更新 更多