0

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"
        }
      }
  ]
}
  • take a look at this post https://stackoverflow.com/questions/16641210/mongoose-populate-with-array-of-objects-containing-ref – Mosius Apr 29 '19 at 03:46

1 Answers1

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

To use populate , define the reference variable in your model and use in another table with this syntax .

Refer link for more details :

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

  • Thanks for your response. I've ran the code you provided and I'm still receiving undefined. I have a reference variable set in both of my models (realm and population), do they look correct? I've read the Mongoose populate docs in its entirety and I can't seem to find the issue with my code. –  Apr 28 '19 at 18:24