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

使用Mongoose时遭遇ReferenceError问题求助

Mongoose ReferenceError 错误排查与解决

错误原因

  • 未声明mongoose变量:代码通过解构仅导入了connect和connection两个成员,但后续执行mongoose.set('debug', true)时,mongoose这个变量并未被定义,触发ReferenceError。
  • 配置项拼写错误:连接配置中的userNewUrlParser是拼写错误,正确应为useNewUrlParser,该错误会导致对应配置不生效。

解决方案

可以通过两种方式修复:

方式一:补充导入mongoose对象

保留原有解构的同时,额外导入完整的mongoose模块:

const mongoose = require('mongoose');
const {connect, connection} = mongoose;

connect( 'mongodb://127.0.0.1:27017/socialNetwork',
    {
        useNewUrlParser: true,
        useUnifiedTopology: true,
    }
);

mongoose.set('debug', true);

module.exports = connection;

方式二:直接使用完整mongoose模块调用所有方法

放弃解构,直接导入mongoose并调用其方法:

const mongoose = require('mongoose');

mongoose.connect( 'mongodb://127.0.0.1:27017/socialNetwork',
    {
        useNewUrlParser: true,
        useUnifiedTopology: true,
    }
);

mongoose.set('debug', true);

module.exports = mongoose.connection;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 14:15:41