英文:
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行和控制台中突出显示的行显示了我的问题。感谢您的任何指导。提前致谢。
英文:
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.
答案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'));
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论