对于我的 NodeJS REST 项目,我正在使用 MongoDB 和 Mongoose ODM :
我的模型架构是:
var playerSchema = new mongoose.Schema({
name: String,
team: mongoose.Schema.Types.ObjectId
})
和服务器端:
app.post('/players', function(req, res) {
Players.find(function(err, players) {
res.json(players);
});
});
响应是:
...
{
"_id": "511a6010e6ca7b0fe0af02ff",
"name": "player-1",
"team": "511a53e2e6ca7b151c09ce8d"
}
...
但我想要像:
{
"_id": "511a6010e6ca7b0fe0af02ff",
"name": "player-1",
"team": {
_id: "511a53e2e6ca7b151c09ce8d"
name: "team-1"
}
}
我做错了什么? 或者我还没有真正理解ObjectId?
谢谢!
答案 0 :(得分:1)
您只是获取具有团队文档ID的玩家文档。
因此,对于每个玩家,您还必须获得团队文档。
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);
});