2015-06-22 71 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

相關問題