在我的数据库中,我有两个集合,玩家和领域。我为他们两个都创建了一个架构,它们彼此引用。我查询玩家集合并尝试填充人口字段。然后,我尝试console.log返回Undefined的结果。
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"
}
}
]
}
答案 0 :(得分:0)
exports.getPlayers = (req, res) => {
Player.find().populate('realm').then((players) => {
console.log(players.realm);
res.json(players);
})
.catch(err => {
console.log(err);
});
}
要使用populate,请在模型中定义参考变量,然后使用此语法在另一个表中使用。
请参阅链接以获取更多详细信息: