2013-02-10 146 views
0

我有以下模式結構爲我的應用程序:貓鼬查詢參考

var User = new Schema({ 
    name: {type: String, required: true}, 
    screen_name: {type: String, required: true, index:{unique:true}}, 
    email: {type: String, required: true, unique:true}, 
    created_at: {type: Date, required: true, default: Date} 
}); 


var Line = new Schema({ 
    user: {type: Schema.ObjectId, ref: 'User'}, 
    text: String, 
    entered_at: {type: Date, required: true, default: Date} 
}); 


var Story = new Schema ({ 
    sid: {type: String, unique: true, required: true}, 
    maxlines: {type: Number, default: 10}, // Max number of lines per user 
    title: {type: String, default: 'Select here to set a title'}, 
    lines: [Line], 
    created_at: {type: Date, required: true, default: Date} 
}); 


var Story = db.model('Story', Story); 
var User = db.model('User', User); 

當我使用我想要的SID輸出在故事線查詢一個故事,但也是用戶SCREEN_NAME。

我目前使用下面的查詢故事:

app.get('/api/1/story/view/:id', function(req, res){ 
    Story.findOne({ sid: req.params.id }, function(err, story){ 
      if (err) { 
      res.json(err); 
     } 
     else if(story == null) { 
      res.json(err); 
     } 
     else{ 
     res.send(story);  
      } 
     }); 
}); 

剛剛帶回的結果是這樣的:

{ 
    "__v": 1, 
    "_id": "5117878e381d7fd004000002", 
    "sid": "DIY0Ls5NwR", 
    "created_at": "2013-02-10T11:42:06.000Z", 
    "lines": [ 
    { 
     "user": "511782cab249ff5819000002", 
     "text": "TESTING", 
     "_id": "51178795381d7fd004000003", 
     "entered_at": "2013-02-10T11:42:13.000Z" 
    } 
    ], 
    "title": "Select here to set a title", 
    "maxlines": 10 
} 

有一個用戶建立與_id但我不完全確定如何輸出故事,併爲它包括用戶screen_name甚至整個用戶信息以及輸出

{ 
    "__v": 0, 
    "screen_name": "Tam", 
    "email": "[email protected]", 
    "name": "Tam", 
    "_id": "511782cab249ff5819000002", 
    "created_at": "2013-02-10T11:21:46.000Z" 
} 

回答

1

我沒有測試它,但你應該能夠使用populate得到充分的用戶文檔象這樣的每lines元素:

Story.findOne({sid: req.params.id}) 
    .populate('lines.user') 
    .exec(function(err, story){ ... 
+0

謝謝,這似乎已經奏效!使用這個邏輯,有沒有辦法看到一個Story's ID的數組? 或者我必須在用戶模式中添加'stories:{type:Schema.ObjectId,ref:'Story'}'然後執行某種操作? – Tam2 2013-02-10 15:21:11

+0

@ Tam2嗯......我不確定你在問什麼。或許更好地將它作爲一個單獨的問題來提供,您可以在其中提供更多細節。 – JohnnyHK 2013-02-10 15:30:45

+0

謝謝約翰尼,我只是問,如果我在原始示例中返回例如'Tam'的用戶,我是否也可以讓它返回storys列表,如 - https://gist.github.com/Tam2/ d54695cb17c4a5a808c0 – Tam2 2013-02-10 15:44:12