Reputation: 4432
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
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