如何在猫鼬和人群中过滤子文档

时间:2018-09-03 07:13:40

标签: mongodb mongoose mongoose-populate

我的文档用户包含以下数据:

{  "name" : "Plantation",
    "image" : "1535695444692.jpg",
    "type" : "csr",
    "user_id" : ObjectId("5b7d598e86acd5b4171a2587"),
    "joining" : [ 
        {
            "csr" : ObjectId("5b8a923f3284ca8451980a43"),
            "volunteer" : ObjectId("5b891c4805540dfc0d541f72"),
            "joined" : false
        }, 
        {
            "csr" : ObjectId("5b8a923f3284ca8451980a43"),
            "volunteer" : ObjectId("5b891c4805540dfc0d541f73"),
            "joined" : true
        }
    ]
}

我只想在csr joining“ 5b8a923f3284ca8451980a43” id子文档上应用过滤器,如果满足此条件,则joining子文档应包含所有匹配的数据,否则joining子文档可以为空。我也想填充joining.volunteer数据。

我使用了以下代码,但它只返回了第一个匹配的子文档。

Users.findOne({ _id: req.params.id },{'joining':{$elemMatch:{csr:'5b7d598e86acd5b4171a2587'}}}).populate('joining.volunteer').then(function (opportunity) {
        return res.json({ opportunity: opportunity });
    }).catch(next);

1 个答案:

答案 0 :(得分:0)

尝试一下:

Users.find({_id: req.params.id},{'joining':{$elemMatch:{csr: CSR_ID }}}).populate({path: 'joining',populate:{
                path: 'volunteer',
                model: 'YOUR volunteer MODEL NAME'
}})