在mongoose中返回内部数据

时间:2017-05-05 09:41:56

标签: node.js mongodb mongoose

我的收藏数据是这样的:

{
"_id" : ObjectId("590ad1f747627f86e585a4af"),
"code" : "IR",
"name" : "Iran",
"background" : "https://vfbdt"
"topics" : [ 
    {
        "name" : "overview",
        "facts" : [ 
            {
                "key" : "capital",
                "value" : "Kuala Lumpur"
            }, 
            {
                "key" : "population",
                "value" : "232424234"
            }, 
            {
                "key" : "reliogion",
                "value" : "Islam"
            }
        ]
    }, 
    {
        "name" : "Good to know",
        "facts" : [ 
            {
                "key" : "key1",
                "value" : "value1"
            }
        ]
    }
]
}

我想通过名称主题名称代码上的过滤器返回所有事实。我写了这段代码,但它没有正常工作,只返回代码过滤所有集合,不考虑 topic.name

 export function getFactsByCodeAndName(req, res, next) {
 Country.find({code:req.params.code,'topics.name':req.params.name})
.exec((err, facts) => {
if (err) return next(err);

return res.status(200).json({
  success: true,
  message: 'Get country',
  data: facts,
     });
   });
}

1 个答案:

答案 0 :(得分:0)

您应该在查询中使用投影 -

Country.find({代码:req.params.code, 'topics.name':{$ elemMatch:{req.params.name}}})

以下是文档链接 -

https://docs.mongodb.com/manual/reference/operator/query/elemMatch/

希望这有帮助。