javascript - $regex 在 MongoDB 中不起作用

标签 javascript node.js mongodb

我知道有很多与 $regex 相关的答案,但我已经尝试了几个小时,但我无法让它工作。

我想要的是在courseName中找到那些包含字母“D”的courses。我究竟做错了什么?请帮我!

我有以下文件:

{
            "firstName": "Sarah",
            "lastName": "Jepsen",
            "age": 27,
            "courses": [
                {
                    "courseName": "Web-Development",
                    "teachers": [
                        {
                            "firstName": "Santiago",
                            "lastName": "Donoso"
                        }
                    ]
                },

                {
                    "courseName": "Databases",
                    "teachers": [
                        {
                            "firstName": "Dany",
                            "lastName": "Kallas"
                        },
                        {
                            "firstName": "Rune",
                            "lastName": "Lyng"
                        }
                    ]
                },
                {
                    "courseName": "Interface-Design",
                    "teachers": [
                        {
                            "firstName": "Roxana",
                            "lastName": "Stolniceanu"
                        }
                    ]
                }
            ]
        }

这是我的查找查询:

student.findCourses = (fcallback) => {
    global.db.collection('students').find({ "courses.courseName": { $regex: "/D/" }, _id: false }).toArray((err, result) => {

        if (err) {
            var jError = { "status": "error", "message": "ERROR -> student.js -> 001" }
            console.log(jError)
            return fcallback(true, jError)
        }
        var jOk = { "status": "ok", "message": "student.js -> found -> 000" }
        console.log(jOk)
        console.log(JSON.stringify(result))
        return fcallback(false, jOk)
    })
}

最佳答案

要获得与您的正则表达式匹配的所有类(class),您必须手动过滤它们。考虑你的情况,使用另一个 courses 数组项:

{
    "courseName": "Unmatching", // no letter "D"
    "teachers": [
        {
            "firstName": "Dany",
            "lastName": "Kallas"
        }
    ]
}

您的查询无论如何都会返回它,因为学生文档中的其他类(class)与您的正则表达式匹配。

你可以做的是:

  1. 查询 (.find()) 匹配类(class)名称的文档
  2. 手动过滤 - 遍历每个项目以检查其名称是否与正则表达式匹配

示例数据:

// 1
{
    "_id" : ObjectId("5a019896f89c24926108e2bf"),
    "firstName" : "Sarah",
    "lastName" : "Jepsen",
    "age" : 27,
    "courses" : [ 
        {
            "courseName" : "Lorem",
            "teachers" : []
        },
        {
            "courseName" : "Ipsum",
            "teachers" : []
        },
        {
            "courseName" : "Dolor",
            "teachers" : []
        },
        {
            "courseName" : "Sit",
            "teachers" : []
        },
        {
            "courseName" : "Dolor 2",
            "teachers" : []
        }
    ]
},
// 2
{
    "_id" : ObjectId("5a019896f89c24926108e2be"),
    "firstName" : "John",
    "lastName" : "Smith",
    "age" : 22,
    "courses" : [ 
        {
            "courseName" : "Dioptry",
            "teachers" : []
        },
        {
            "courseName" : "Dino",
            "teachers" : []
        },
        {
            "courseName" : "A",
            "teachers" : []
        },
        {
            "courseName" : "B",
            "teachers" : []
        },
        {
            "courseName" : "C",
            "teachers" : []
        }
    ]
}

查询&过滤代码:

student.findCourses = (fcallback) => {

    var regexp = new RegExp('D');

    global.db.collection('students').find({ "courses.courseName": { $regex: regexp } }, { _id: 0, courses: 1 } }).toArray((err, result) => {

        // here, you'll receive:
        // [{ courses: [] }, { courses: [] }]
        // with all the courses inside
        // no matter if their names match the given regex
        // as it's enough that one of them does
        // to return the whole document

        // filtering:
        var filtered = result.map(student => {
            student.courses = student.courses.filter(course => regexp.test(course.courseName));
            return student;
        });

        // now, your filtered has exactly the same format
        // [{ courses: [] }, { courses: [] }]
        // but only with courses matching the regexp inside it

        console.log(JSON.stringify(filtered);

        // what you can do to get flat courses array is:
        var flat = filtered.reduce((p, c) => p.concat(c.courses), [])

        console.log(JSON.stringify(flat));


        if (err) {
            var jError = { "status": "error", "message": "ERROR -> student.js -> 001" }
            console.log(jError)
            return fcallback(true, jError)
        }
        var jOk = { "status": "ok", "message": "student.js -> found -> 000" }
        console.log(jOk)
        console.log(JSON.stringify(result))
        return fcallback(false, jOk)
    })
}

关于javascript - $regex 在 MongoDB 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47162993/

相关文章:

javascript - 我不知道 var 的范围

javascript - NodeJs 与 EC2 上的 ubuntu 服务器对话

node.js - 哪个ffmpeg命令序列可以生成视频的第一帧【Node.js app需要缩略图】

javascript - Node.JS 上的服务器发送事件

node.js - MongoDB:如何将嵌套数组分组到一个文档中?

php - 将每个mongodb记录输出到html表中

mongodb - 已安装 MongoDB,但它未显示在程序文件或卸载或更改程序中

asp.net - JavaScript 触发 - vb.net api 调用的反射?

javascript 表单选择姓名和号码

javascript - 类型 'products' 上不存在属性 'Readonly<{}>'