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 查询故事时,我希望它输出该故事中的行以及用户屏幕名称。

目前我正在使用以下内容来查询故事:

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": "test@test.com",
  "name": "Tam",
  "_id": "511782cab249ff5819000002",
  "created_at": "2013-02-10T11:21:46.000Z"
}
4

1 回答 1

1

我还没有测试过它,但你应该能够使用它populate来获取每个lines元素的完整用户文档,如下所示:

Story.findOne({sid: req.params.id})
    .populate('lines.user')
    .exec(function(err, story){ ...
于 2013-02-10T14:51:07.950 回答