When you query Team
, the docs that are returned by Mongoose have the same structure as your schema, so you need to pull out the player you're looking for from that structure.
Use the $
positional projection operator to identify the first player matched in your query so that your result only contains that player in the players
array field:
models.Team.findOne(
{'players._id': req.params.id },
{'players.$': 1},
function(err, team) {
if (err || !team || !team.players || !team.players.length) {
res.json({error: 'player not found.'});
} else {
res.json(team.players[0]);
}
}
);
Note that findOne
is used instead of find
because you're only looking to find the single team containing that player.