【问题标题】:Mongoose query with find and as a result the field name where i found results使用 find 进行 Mongoose 查询,结果是我找到结果的字段名称
【发布时间】:2017-04-19 07:20:03
【问题描述】:

我试图通过查询获得我找到正则表达式的字段,例如:

如果我在 facebook 字段中找到结果;

假设我的 req.body.key = 'crazy' 并且在我的数据库中,我在 facebook 字段中有 'crazy'。作为查询的结果,我想要我的 CitizenProfile 模型更多的字段或我找到结果的字段。在这种情况下,字段名称 'facebook'

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

【问题讨论】:

    标签: javascript mongodb mongoose mongodb-query


    【解决方案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);
        });
    });
    

    【讨论】:

    • 谢谢是我想要的; D
    猜你喜欢
    • 2020-11-24
    • 1970-01-01
    • 1970-01-01
    • 2023-03-15
    • 2018-12-22
    • 2020-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多