1

我在我的NodeJS REST项目中使用MongoDBMongoose 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?

谢谢!

4

1 回答 1

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);
});
于 2013-02-14T07:39:41.780 回答