Mongoose查询参考

时间:2013-02-10 14:06:12

标签: node.js mongodb express mongoose

我的应用程序具有以下架构结构:

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查询Story时,我希望它输出该故事中的行以及用户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": "test@test.com",
  "name": "Tam",
  "_id": "511782cab249ff5819000002",
  "created_at": "2013-02-10T11:21:46.000Z"
}

1 个答案:

答案 0 :(得分:1)

我尚未对其进行测试,但您应该可以使用populate获取每个lines元素的完整用户文档,如下所示:

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