Mongoose连接到数据库,但仍然在mongoose.connect后响应.catch方法?

huangapple go评论61阅读模式
英文:

Mongoose connecting to database but still responding to .catch method after mongoose.connect?

问题

所以我正在学习Node.js的基础知识,并使用Mongoose连接到MongoDB。我可以成功连接到数据库并在数据库上执行获取和发布方法,但是尝试连接到数据库时,返回一个Promise的mongoose.connect方法既使用.then()又使用.catch(),我不确定为什么,因为Promise可以返回resolve或reject。resolve应该调用.then(),而reject应该调用.catch()...

第16行和控制台中突出显示的行显示了我的问题。感谢您的任何指导。提前致谢。

Mongoose连接到数据库,但仍然在mongoose.connect后响应.catch方法?

英文:

So I am learning the basics of Nodejs and using Mongoose to connect to mongodb. I can successfully connect to database and perform get and post methods on database, but when trying to connect to database, the mongoose.connect method that returns a promise, is working with both .then() and .catch() and I am not sure why, since a promise can either return a resolve or a reject. resolve should call .then() and reject should call .catch()...

Line 16 and the highlighted line in console show my issue. Any guidance is appreciated. Thanks in advance.

Mongoose连接到数据库,但仍然在mongoose.connect后响应.catch方法?

答案1

得分: 1

你没有正确处理连接的 promise 拒绝/解决。尝试将你的连接代码更改为以下内容:

mongoose
  .connect('mongodb://127.0.0.1:27017/vidly')
  .then(() => console.log('Connected to Mongoose...'))
  .catch(err => console.error('Could not connect to mongodb'));
英文:

You are not handle the connect promise reject\resolve properly. Try and change your connect code to something like

mongoose
  .connect('mongodb://127.0.0.1:27017/vidly')
  .then(() => console.log('Connected to Mongoose...'))
  .catch(err => console.error('Could not connect to mongodb'));

huangapple
  • 本文由 发表于 2023年1月4日 14:50:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/75001837.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定