问题描述
以下是我的mongodb文档的外观(当然是json格式)
Here is an idea of what my mongodb document looks like (json format of course)
[
{
_id: 50,
team_name: 'bulls',
players: [
{
_id: 100,
player_name: 'Jokim'
}
]
}
]
因此,当路线api/teams/50/players/100
命中时,我要投放Jokim
.我正在尝试阅读有关猫鼬嵌套文档的其他文章,但是我似乎无法在这里找到答案.我只想找到文档,我已经设置了路由.
So when the route api/teams/50/players/100
hits I want to serve Jokim
. I am trying to read other posts on mongoose nested documents, but I can't seem to find an answer for what I am looking for here. I simply want to find the document, I already have the route setup.
models.Team.find({'players._id':req.params.id }, function(err, player) {
if (err) {
res.json({error: 'player not found.'});
} else {
res.json(player);
}
});
这是我的SCHEMA
This is my SCHEMA
var Team = new Schema({
team_name: { type: String },
players: [
{
player_name: { type: String },
points: { type: Number },
made_one: { type: Number },
made_two: { type: Number },
made_three: { type: Number },
missed_one: { type: Number },
missed_two: { type: Number },
missed_three: { type: Number },
percentage: { type: Number },
assists: { type: Number },
rebounds: { type: Number },
steals: { type: Number },
blocks: { type: Number },
fouls: { type: Number },
feed: { type: String },
facebook_id: { type: Number }
}
],
points: { type: Number },
made_one: { type: Number },
made_two: { type: Number },
made_three: { type: Number },
missed_one: { type: Number },
missed_two: { type: Number },
missed_three: { type: Number },
percentage: { type: Number },
assists: { type: Number },
rebounds: { type: Number },
steals: { type: Number },
blocks: { type: Number },
fouls: { type: Number },
feed: { type: String }
});
推荐答案
查询Team
时,猫鼬返回的文档与您的架构具有相同的结构,因此您需要拔出要播放的播放器从该结构中寻找.
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.
使用 $
位置投影算子来确定查询中匹配的第一个玩家,以便您的结果仅在players
数组字段中包含该玩家:
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]);
}
}
);
请注意,使用findOne
代替find
,因为您只是在寻找包含该球员的单个球队.
Note that findOne
is used instead of find
because you're only looking to find the single team containing that player.
这篇关于猫鼬找到嵌套模型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!