2017-04-18 76 views
0

我想有作为我查询的结果,我找到了正则表达式,例如现场:如果我发现结果中的Facebook以查找和结果字段名猫鼬查询,我发现结果

领域;

让我们说我的req.body.key ='疯狂',在我的数据库里我疯了'在Facebook领域。作为查询的结果,我希望我的CitizenProfile模型更多地发现结果的字段或字段。在这种情况下,字段名称'脸谱'

Obs:这个查询已经给模型我只需要字段或字段名称,它发现匹配的正则表达式。 这可以实现吗?谢谢!

app.post('/v1/profile/search', (req, res) => { 
    async.waterfall([ 
     function (next) { 
      CitizenProfile.find({ 
       $or: [{'first_name': {$regex: req.body.key, $options:'i'}}, {'middle_name': {$regex: req.body.key, $options:'i'}}, 
        {'last_name': {$regex: req.body.key, $options:'i'}}, {'email': {$regex: req.body.key, $options:'i'}}, 
        {'facebook': {$regex: req.body.key, $options:'i'}}, {'linkedin': {$regex: req.body.key, $options:'i'}}, 
        {'skills': {$regex: req.body.key, $options:'i'}}], 
       'id_citizen': {$ne: req.body.id_citizen}, 
       'is_hidden': {$ne: true} 
      }) 
       .exec(function (err, data) { 
        ... 

回答

1

我不认为MongoDB具有这种功能(如果我错了,请纠正我的错误)。

由于您只取回与正则表达式匹配的文档,因此您必须再次在这些相同的文档上应用正则表达式来查找字段。

未经测试,但我认为你会做这样的事情

let regex = new RegExp(req.body.key, 'i'); 

CitizenProfile.find({ 
    $or: [ 
     { 'first_name': regex }, 
     { 'middle_name': regex }, 
     { 'last_name': regex }, 
     { 'email': regex }, 
     { 'facebook': regex }, 
     { 'linkedin': regex }, 
     { 'skills': regex } 
    ], 
    'id_citizen': { $ne: req.body.id_citizen }, 
    'is_hidden': { $ne: true } 
}).exec(function (err, profiles) => { 
    // loop through found documents 
    profiles.forEach(function (profile) { 
     profile = profile.toJSON(); 
     // filter fields based on regular expression 
     let keys = Object.keys(profile).filter(k => regex.test(profile[k])); 
     // do something with keys 
     console.log(keys); 
    }); 
}); 
+0

感谢就是我一直在寻找; d – michelpm1