首页 > 解决方案 > mongo中是否有一个函数来查找数组中是否存在元素?

问题描述

我正在尝试编写一个查询,以使数组中不存在特定的字符串。我的架构是:

    _id: {
        type: String,
        required: true
    },
    ...
    meta: {
        user_likes: {
            type: [String],
        },
        user_dislikes: {
            type: [String],
        },
        user_liked_by: {
            type: [String],
        },
        user_matches: {
            type: [String],
        },
    ...
    },

meta其他文档的key中的对象中的数组内容_id,类型为String.

现在我有一个 API 端点来处理这个查询,它是这样的:

router.post('/fetchUsersForClient', async function (req, res) {
    /* Body
    {
        "client_id" : String
    }
    */
    try {
            var client_id = req.body.client_id;
            const users = await SampleUser.find(); //query here
            res.json(users);
        }
        
    } catch (error) {
        res.send({ message: error });
    }
});

我想编写一个查询,使得该变量client_id不存在于meta对象的任何数组中并且client_id不等于_id任何文档。

编辑:我尝试使用此查询来获取我的结果,但我不知道如何"1"在查询中替换。

{
    "_id" : {
        $ne : "1"
    },
    $and : [
        {
            "meta.user_likes" : {
                $not : /.*1.*/i
            }
        },
        {
            "meta.user_dislikes" : {
                $not : /.*1.*/i
            }
        },
        {
            "meta.user_matches" : {
                $not : /.*1.*/i
            }
        } 
    ]
}

标签: javascriptnode.jsmongodbmongoosemongodb-query

解决方案


我通过修改给出的代码找到了这个问题的答案。在这里,我使用了一个单独的常量来初始化一个正则表达式模式。这是我的方法:

router.post('/fetchUsersForClient', async function (req, res) {
    /* Body
    {
        "client_id" : String
    }
    */
    try {
            var client_id = req.body.client_id;
            var expr = '.*var.*'
            expr = expr.replace("var", client_id);
            const chkExp = new RegExp(expr);
            const users = await User.find(
                {
                    "_id": {
                        $ne: client_id
                    },
                    $and: [
                        {
                            "meta.user_likes": {
                                $not: chkExp
                            }
                        },
                        {
                            "meta.user_liked_by": {
                                $not: chkExp
                            }
                        },
                        {
                            "meta.user_dislikes": {
                                $not: chkExp
                            }
                        },
                        {
                            "meta.user_matches": {
                                $not: chkExp
                            }
                        }
                    ]
                }
            );
            res.json(users);
    } catch (error) {
        console.log(error);
        res.send({ message: error });
    }
});


推荐阅读