mongoose:如何在类型引用的属性上查询具有条件的模型

时间:2016-01-21 02:58:00

标签: node.js mongodb mongoose

var UserSchema=new Schema({
        username: {
            type: String,
            required: 'UserName is required'
        }
    });

var PostingSchema=new Schema({

        creator: {
            type: Schema.ObjectId,
            ref: 'User',
            required:true
        }
    });

我想检索给定用户名的帖子。我正在以下面的方式做,这是行不通的。

Posting
            .find({ 'creator.username': req.params.username })
            .populate('creator', 'firstName lastName fullName username profile_pic')
            .exec(function(err, postings){
                if (err){
                    res.status(501).json({ error: err});
                } else {
                    res.json(postings);
                }
            });

我得到了空结果数组。可能是查询条件有问题。如何在ref对象上应用条件。有人可以纠正这个吗?

1 个答案:

答案 0 :(得分:0)

请参阅Query populate

 .populate({ 
      path: 'creator',
      match: { username: req.params.username })

 .populate('creator', null,  { username: req.params.username })