1

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?

laser
  • 1,388
  • 13
  • 14
user59388
  • 159
  • 1
  • 10

2 Answers2

0

You can use nested code like

Match.find(function (err, matches) {
    if (err) {
      console.log(err);
      return next(err);
    }
    Game.find(function (err, games) {
        if (err) {
          console.log(err);
          return next(err);
        }
        Users.find(function (err, user) {
            if (err) {
              console.log(err);
              return next(err);
            }

            res.json({matches:matches, games:games, user:user});
          });
      });
  });
  • I've edited the question with better wording. I've already attempted to nest with a while loop through all the matches but got a headers sent error – user59388 May 11 '15 at 08:23
  • if you have a loop and in loop you are using this code then you will face such issue coz you have "res.json" that return responce by setting header. So in that case you can use "async" module, here you will find ref https://github.com/caolan/async – Abhishek Mishra May 11 '15 at 08:46
0

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

Michael Malura
  • 1,131
  • 2
  • 13
  • 30