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

Mongoose连接Promise的catch调用报错,如何正确使用catch?

问题分析与修复方案

问题原因

  • 链式调用位置错误:你把.catch()写在了.then()的回调函数内部,跟在console.log()后面。但console.log()执行后返回的是undefined,对undefined调用.catch()就会触发你看到的"Cannot read properties of undefined (reading 'catch')"错误。.catch()应该直接链式挂载在.then()方法的后面,用来捕获整个mongoose.connect()Promise链的错误。
  • 拼写错误:代码里有两处笔误:useCreatIndex应为useCreateIndex,DB conecttion successful里的conecttion应为connection,这些小错误可能引发其他意外问题。

修复后的代码

mongoose
  .connect(DB, {
    useNewUrlParser: true,
    useCreateIndex: true,
    useFindAndModify: false,
  })
  .then(() => {
    console.log('DB connection successful')
  })
  .catch(() => console.log('Error connecting to DB'));

const port = 3000;
app.listen(port, () => {
  console.log(`app running on port ${port}`);
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 11:27:28