You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Express应用员工搜索功能报错:Cannot read property 'includes' of undefined

问题分析与解决

错误根源

Employee.find({})返回的是所有员工组成的数组,而非单个员工对象。你试图访问数组的firstName属性,这个属性根本不存在,因此触发了Cannot read property 'includes' of undefined错误。此外代码还有两处问题:

  • 先拉取全量数据再在内存过滤,数据量大时效率极低
  • res.render('No match found')用法错误,render的第一个参数必须是EJS模板文件名,不能直接传字符串

修正后的代码

const searchEmployees = wrapAsync(async(req, res, next) => {
    const info = req.query.searchEmployees?.trim(); // 去除首尾空格,可选链避免参数未定义时报错

    // 处理空输入的情况
    if (!info) {
        return res.render('employees/error', { message: '请输入搜索内容' });
    }

    // 让MongoDB直接执行模糊匹配查询,效率远高于全量拉取后过滤
    // $regex实现不区分大小写的模糊搜索,若需精确匹配,直接用 { firstName: info }
    const matchedEmployees = await Employee.find({
        firstName: { $regex: info, $options: 'i' }
    });

    if (matchedEmployees.length > 0) {
        res.render('employees/search', { employees: matchedEmployees });
    } else {
        // 渲染错误提示模板(需确保你有对应的employees/error.ejs文件)
        res.render('employees/error', { message: '未找到匹配的员工' });
    }
})

关键改动说明

  • 直接通过MongoDB查询语法过滤数据,避免全量拉取后在内存中处理,大幅提升性能
  • 添加了搜索参数的校验,处理空输入的边界情况
  • 修正res.render的用法,使用合法的模板文件名传递提示信息
  • 将变量名从employee改为matchedEmployees,更贴合数组的语义
  • 若需要精确匹配员工姓名,只需把查询条件改为{ firstName: info }即可

内容的提问来源于stack exchange,提问作者Robert Barr

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 01:12:55