使用Mongoose连接MongoDB时触发报错:Mongoose.prototype.connect() no longer accepts a callback
Mongoose连接MongoDB时触发报错:Mongoose.prototype.connect() no longer accepts a callback
嘿,这个问题我之前踩过坑!报错的原因很直白——你用的应该是Mongoose 6.x及以上的版本,这个版本已经彻底移除了connect()方法接受回调函数的支持,得换成Promise或者async/await的写法才行。
先看看你原来的代码问题出在哪:
const mogoURI = "mongodb://localhost:27017/?directConnection=true"; const connectToMongo = ()=>{ mongoose.connect(mogoURI,()=>{ console.log("Connected to Mongo Successfully"); }) } module.exports = connectToMongo;
给你两种靠谱的解决方案,选哪个都行:
方案一:用Promise的then/catch处理
这种写法延续了异步链式调用的风格,适合习惯Promise语法的同学:
const mongoose = require('mongoose'); const mogoURI = "mongodb://localhost:27017/?directConnection=true"; const connectToMongo = ()=>{ mongoose.connect(mogoURI) .then(() => console.log("Connected to Mongo Successfully")) .catch(err => console.error("Failed to connect to Mongo:", err)); } module.exports = connectToMongo;
方案二:用async/await(推荐更简洁的写法)
async/await让异步代码看起来像同步代码,可读性更高,也更方便处理错误:
const mongoose = require('mongoose'); const mogoURI = "mongodb://localhost:27017/?directConnection=true"; const connectToMongo = async ()=>{ try { await mongoose.connect(mogoURI); console.log("Connected to Mongo Successfully"); } catch (err) { console.error("Failed to connect to Mongo:", err); // 如果需要上层处理错误,可以抛出这个异常 throw err; } } module.exports = connectToMongo;
另外提醒一句,这样修改后还能更好地捕获连接失败的错误信息,方便你排查数据库连接的各种问题,比如端口不对、MongoDB没启动之类的~
备注:内容来源于stack exchange,提问作者chester Thapa
相关产品推荐
相关产品推荐

