I'm learning the MEAN stack and want to select multiple models when routing with express. I need to select one model then based on it's values a few others. Here's the main model:
var mongoose = require('mongoose');
var MatchSchema = new mongoose.Schema({
title: String,
type: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Game' }],
owner: [{ type: mongoose.Schema.Types.ObjectId, ref: 'User' }],
players: [{ type: mongoose.Schema.Types.ObjectId, ref: 'User' }]
});
mongoose.model('Match', MatchSchema);
Based on the type owner and players I need to select Game and User models, but I'm stuck in doing so. Here's my current route, which only selects the Matches model.
router.get('/games', function (req, res, next) {
Match.find(function (err, matches) {
if (err) {
console.log(err);
return next(err);
}
res.json(matches);
});
});
So I need to loop through all of the matches and for every one select the Game model that belongs to it's type and the User models that belong to the owner and players, how would I go about doing that?
If i understand your question correct then you have to populate your sub documents.
Mongoose has the ability to do this for you. Basically you have to do something like this:
router.get('/games', function (req, res, next) {
Match
.find({})
.populate('type').populate('owner').populate('players')
.exec(function (err, matches) {
if (err) return handleError(err);
res.json(matches);
});
});
For more information look at the mongoose docs: http://mongoosejs.com/docs/populate.html