2015-06-22 72 views
1

我有一个API可以查找表中的所有数据,但在该表的内部,我具有对用户的对象ID引用。在MongoDB中查找所有包含相关对象标识的名称

表1 - 故事| 表2 - 用户

api.get('/all_stories', function(req, res) { 
    Story.find({}, function(err, stories) { 
     if (err) { 
      res.send(err); 
      return; 
     } 
     res.json(stories); 
    }); 
}); 

所以这个API显然检索所有的数据表的故事里面,并返回它作为JSON。

creator: { type: Schema.Types.ObjectId, ref: 'User' }, 
content: String, 
created: { type: Date, default: Date.now() } 

如何使用ref:'User'在User表中查找并显示其他数据colum。 或者,也许这样返回它为JSON。

回答

1

你需要使用populate做到这一点:

http://mongoosejs.com/docs/2.8.x/docs/populate.html

Story 
.find({}) 
.populate('creator') 
.exec(function (err, stories) { 
     if (err) { 
      res.send(err); 
      return; 
     } 
     //stories now contains an array of Story, with their creator property populated with the user document 
     res.json(stories); 
}) 

看来你使用相同/非常相似的模型的例子在文档...

+1

哇谢谢你。我一直试图寻找类似的东西,但我不知道如何说出来。 – Photonic

+0

没问题,很高兴我能帮到你 – Alex

相关问题