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
相关产品推荐
相关产品推荐

