MongoDB ObjectId用法

时间:2013-02-12 15:52:41

标签: node.js mongodb mongoose objectid

对于我的 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?

谢谢!

1 个答案:

答案 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);
});