简体   繁体   English

猫鼬查询与结果和结果我发现结果的字段名称

[英]Mongoose query with find and as a result the field name where i found results

I'm trying to have as a result of my query the field i found the regex, example : 由于查询的原因,我试图将字段找到正则表达式,例如:

If i find the result in facebook field; 如果我在facebook字段中找到结果;

Lets say my req.body.key = 'crazy' and inside my db i have 'crazy' in facebook field. 假设我的req.body.key ='crazy',在我的数据库中,我在facebook字段中拥有'crazy'。 I want as a result of the query my CitizenProfile model more the field or fields i found the result. 由于查询我的CitizenProfile模型,我想要更多我找到结果的字段。 In this case the field name 'facebook' 在这种情况下,字段名称为“ facebook”

Obs: This query is already giving the model i just need the field or fields name where it found match with regex. Obs:这个查询已经给了模型,我只需要找到与正则表达式匹配的字段名称即可。 Can this be achieve? 能做到吗? Thanks! 谢谢!

    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) {
                   ...

I don't think MongoDB has that kind of feature (correct me anyone if I am wrong). 我不认为MongoDB具有这种功能(如果我错了,请改正任何人)。

Since you are only getting back the documents matching the regular expression, you'll have to apply the regular expression on those same documents again to find the fields. 由于您只取回与正则表达式匹配的文档,因此必须将正则表达式再次应用于这些相同的文档以查找字段。

Untested but I think you would do something like 未经测试,但我认为您会做类似的事情

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);
    });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM