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

Node.js TypeError求助:无法读取undefined的'n'属性

技术求助:特定路由触发MongoDB TypeError错误

访问某一特定路由时持续触发以下错误,其他路由运行正常,求解决办法。

错误信息

/home/sherif/Desktop/fmsD/node_modules/mongodb/lib/utils.js:132
      throw err;
      ^

TypeError: Cannot read properties of undefined (reading 'n')
    at /home/sherif/Desktop/fmsD/node_modules/mongodb/lib/operations/collection_ops.js:237:46
    at /home/sherif/Desktop/fmsD/node_modules/mongodb/lib/utils.js:414:17
    at executeCallback (/home/sherif/Desktop/fmsD/node_modules/mongodb/lib/utils.js:406:9)
    at handleCallback (/home/sherif/Desktop/fmsD/node_modules/mongodb/lib/utils.js:128:55)
    at /home/sherif/Desktop/fmsD/node_modules/mongodb/lib/operations/cursor_ops.js:218:62
    at handleCallback (/home/sherif/Desktop/fmsD/node_modules/mongodb/lib/utils.js:128:55)
    at completeClose (/home/sherif/Desktop/fmsD/node_modules/mongodb/lib/cursor.js:887:14)
    at /home/sherif/Desktop/fmsD/node_modules/mongodb/lib/cursor.js:898:37
    at AggregationCursor.Cursor._endSession (/home/sherif/Desktop/fmsD/node_modules/mongodb-core/lib/cursor.js:193:5)
    at AggregationCursor.Cursor._endSession (/home/sherif/Desktop/fmsD/node_modules/mongodb/lib/cursor.js:226:59)
    at AggregationCursor.Cursor.close (/home/sherif/Desktop/fmsD/node_modules/mongodb/lib/cursor.js:898:19)
    at /home/sherif/Desktop/fmsD/node_modules/mongodb/lib/operations/cursor_ops.js:218:23
    at handleCallback (/home/sherif/Desktop/fmsD/node_modules/mongodb-core/lib/cursor.js:202:5)
    at /home/sherif/Desktop/fmsD/node_modules/mongodb-core/lib/cursor.js:560:38
    at /home/sherif/Desktop/fmsD/node_modules/mongodb-core/lib/cursor.js:568:46
    at AggregationCursor.Cursor._endSession (/home/sherif/Desktop/fmsD/node_modules/mongodb-core/lib/cursor.js:193:5)

触发错误的路由代码

router.get('/', [ensureAuthenticated, isAdmin, readAccessControl], async (req, res) => {

    const perPage = 8;
    const page = req.query.page || 1;
    const skip = ((perPage * page) - perPage);

    // const dept = await Department.find();
    const course = await Course.find().skip(skip).limit(perPage);

    if (course) {
        const pages = await Course.find().countDocuments();

        res.render('courses/index', {
            title: 'Courses',
            breadcrumbs: true,
            search_bar: true,
            // dept: dept,
            course: course,
            current: parseInt(page),
            pages: Math.ceil(pages / perPage)
        });
    } else if (dept) {
        res.render('courses/index', {
            title: 'Courses',
            breadcrumbs: true,
            search_bar: true,
            // dept: dept
        });
    } else {
        req.flash('error_msg', 'No department found');
        res.redirect('/');
    }
});

问题分析与解决办法

这个报错是MongoDB驱动处理游标时的异常,主要原因可能是MongoDB驱动和Mongoose版本不兼容,另外你的代码也存在几处逻辑问题,加剧了出错概率:

  • Course.find()返回的是数组,哪怕没有数据也是空数组,所以if (course)永远为真,后面的else if (dept)分支根本不会执行,而且dept变量被注释掉了,这里还存在未定义变量的隐患。
  • 两次调用Course.find(),既浪费数据库资源,也增加了游标操作出错的可能。

具体修复步骤:

  1. 检查版本兼容性:
    对照Mongoose官方文档的版本兼容表,调整MongoDB驱动和Mongoose的版本至匹配组合,这类游标异常很多都是版本不匹配导致的。

  2. 重构路由代码:
    合并查询逻辑,添加异常捕获,处理好参数类型:

    router.get('/', [ensureAuthenticated, isAdmin, readAccessControl], async (req, res) => {
        try {
            const perPage = 8;
            // 将page转为数字类型,避免字符串运算错误
            const page = parseInt(req.query.page) || 1;
            const skip = (page - 1) * perPage;
    
            // 并行执行列表查询和总数统计,提升性能
            const [courseList, totalCourses] = await Promise.all([
                Course.find().skip(skip).limit(perPage),
                Course.countDocuments()
            ]);
    
            const totalPages = Math.ceil(totalCourses / perPage);
    
            res.render('courses/index', {
                title: 'Courses',
                breadcrumbs: true,
                search_bar: true,
                course: courseList,
                current: page,
                pages: totalPages
            });
        } catch (err) {
            console.error('加载课程列表失败:', err);
            req.flash('error_msg', '加载课程列表失败,请稍后重试');
            res.redirect('/');
        }
    });
    
  3. 清理无效代码:
    删除注释掉的dept相关代码,避免代码混乱和潜在的变量错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 20:10:33