【问题标题】:How can I fix TypeError: Cannot read properties of undefined (reading 'split') in mongoose?如何修复 TypeError: Cannot read properties of undefined (reading \'split\') in mongoose?
【发布时间】:2022-09-24 16:57:47
【问题描述】:

我刚刚使用 mongoose 连接了 mongoDB。
但我收到错误TypeError: Cannot read properties of undefined (reading \'split\')
我该如何解决这个错误?

这是我的代码

export const dbConnect = async () => {
  mongoose.connect(process.env.NEXT_PUBLIC_MONGO_URI);
  const db = mongoose.connection;
  db.on(\'error\', function () {
    console.log(\'db connection failed!\');
  });
  db.once(\'open\', function () {
    console.log(\'db connected!\');
  });
};

我正在使用猫鼬版本 6.5.3,下一个版本 12.2.5

  • 您的问题很可能不是在您显示的代码中引起的。您至少可以将错误的完整堆栈跟踪添加到您的问题中吗?

标签: javascript mongodb mongoose next.js


【解决方案1】:

process.env.NEXT_PUBLIC_MONGO_URI 的价值是什么

格式应该像

mongoose.connect('mongodb://localhost/myapp');

mongoose.connect('mongodb://username:password@host:port/database?options...');

【讨论】:

  • 我的 URI 是“mongodb+srv://username:password@serverURI”。我在 mongodb 主页中获得了 URI。我在其他项目中使用相同的 URI 成功连接了 db,所以我认为 URI 是正确的..
  • 您需要更改上面的广告 remove +srv
  • 就像你说的,我从 URI 中删除了 +src。但是会发生同样的错误。
  • 添加端口和数据库
【解决方案2】:

我认为问题出在连接功能上。您提供的 URI 可能是错误的。尝试在函数之前记录它,以确保它是正确的 uri。

https://www.mongodb.com/docs/manual/reference/connection-string/

在这里您可以找到正确的连接字符串格式。

【讨论】:

  • 我的 URI 是 mongodb+srv://${name}:${password}@${serverURI},我在 mongodb 主页中获得了 URI。我在其他项目中使用相同的 URI 成功连接了 db,所以我认为 URI 是正确的。
  • 我发现了一篇关于同样问题的帖子,也许它会有所帮助:github.com/Automattic/mongoose/issues/11558“实际上这是我的错,参考引用的是模式而不是模型。” - 那是那个帖子中的解决方案。
【解决方案3】:

当您尝试在客户端代码中使用 Mongoose 时,就会发生这种情况。

Mongoose 在其代码的某处检查它正在使用的节点安装的版本。

在浏览器中运行,没有process.versions.node 这样的东西,因此出现错误。

【讨论】:

    猜你喜欢
    • 2021-12-31
    • 2021-11-10
    • 2022-01-11
    • 1970-01-01
    • 2022-10-09
    • 2022-07-21
    • 2022-07-22
    • 2021-11-03
    • 2021-11-08
    相关资源
    最近更新 更多