Reputation: 151
Game schema
const { Schema, model } = require('mongoose');
const gameSchema = Schema({
_id: Schema.Types.ObjectId,
name: { type: String, required: true },
description: String,
calc: [{ type: Schema.Types.ObjectId, ref: 'Calc' }]
});
module.exports = model('Game', gameSchema);
Calc schema
const { Schema, model } = require('mongoose');
const calcSchema = Schema({
_id: Schema.Types.ObjectId,
preset: { type: String, required: true },
datasets: [{ type: Schema.Types.ObjectId, ref: 'Dataset' }],
model: String,
});
module.exports = model('Calc', calcSchema, 'calc');
GET Games route
router.get('/', passport.authenticate('jwt', { session: false }), (req, res) => {
Game.find()
.select('_id name calc')
.populate('calc')
.then(games => res.status(200).json(games))
.catch(err => res.status(500).json({ error: err }));
});
Instead of populating calc property with Calc objects, replacing the ids, calc property turns into an empty array. How do I use populate correctly? Is there an obvious mistake I made in my code?
In short: populate() results in calc: [] instead of calc: [{Calc object}, ...]
Upvotes: 1
Views: 491
Reputation: 7136
In your case you are trying to populate an array of document (and not only one document) so you should use the Model.populate() method instead.
Game.find()
.select('_id name calc')
.then(games => Game.populate(games, { path: 'calc' }))
.then(games => res.status(200).json(games))
.catch(err => res.status(500).json({ error: err }));
Upvotes: 1