【问题标题】:How to filter subdocument in mongoose along with population如何过滤猫鼬中的子文档和人口
【发布时间】:2018-09-03 17:37:44
【问题描述】:

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

{  "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
        }
    ]
}

我只想对 joining 子文档应用过滤器,其中 csr id"5b8a923f3284ca8451980a43" 如果此条件匹配,则 joining 子文档应包含所有匹配数据,否则 @987654325 @子文档可以为空。我还想填充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);

【问题讨论】:

    标签: mongodb mongoose mongoose-populate


    【解决方案1】:

    试试这个:

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

    【讨论】:

      猜你喜欢
      • 2023-04-02
      • 2019-05-31
      • 2020-01-04
      • 2021-12-25
      • 1970-01-01
      • 2016-11-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多