【问题标题】:MongoDB ObjectId usageMongoDB ObjectId 用法
【发布时间】:2013-02-14 15:39:41
【问题描述】:

我将 MongoDBMongoose ODM 一起用于我的 NodeJS REST 项目:

我的模型架构是:

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?

谢谢!

【问题讨论】:

标签: node.js mongodb mongoose objectid


【解决方案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);
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-01-16
    • 1970-01-01
    • 2015-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-15
    • 2015-02-26
    相关资源
    最近更新 更多