In my database I have two collections, players and realms. I have created a schema for both of them and they reference each other. I query the players collection and try to populate the population field. I then try to console.log the results which returns Undefined.
player.js (model)
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 (model)
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 (controller)
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);
});
}
The results I expect would look something like this:
{
"players": [
{
"name": "Grubby",
"wins": 2397,
"losses": 632,
"race": "Orc",
"realm": {
"_id": "5ca1985ae03dd80007aa008f",
"name": "EU"
}
}
]
}