frx08
frx08

Reputation: 4432

MongoDB ObjectId usage

I'm using MongoDB with Mongoose ODM for my NodeJS REST project:

my model schema is:

var playerSchema = new mongoose.Schema({
    name: String,
    team: mongoose.Schema.Types.ObjectId
})

and server side:

app.post('/players', function(req, res) {
  Players.find(function(err, players) {
    res.json(players);
  });
});

the response is:

...
{
  "_id": "511a6010e6ca7b0fe0af02ff",
  "name": "player-1",
  "team": "511a53e2e6ca7b151c09ce8d"
}
...

but I want something like:

{
  "_id": "511a6010e6ca7b0fe0af02ff",
  "name": "player-1",
  "team": {
    _id: "511a53e2e6ca7b151c09ce8d"
    name: "team-1"
  }
}

What I'm doing wrong? or I haven't really understood the ObjectId?

Thanks!

Upvotes: 1

Views: 726

Answers (1)

subbu
subbu

Reputation: 254

You are only fetching the players document which have id of team document.

So for each player you have to get team doc also.

Players.find(function(err, players) {
   for(var i in players){
      Team.findById(players[i].team,function(error,teams){
          players[i].team = teams;
      })
   }
    res.json(players);
});

Upvotes: 1

Related Questions