Node.js用async/await经Mongoose连接MongoDB出现弃用告警如何解决
问题根因
你代码中存在两处逻辑错误导致重复发起不带参数的Mongo连接,外加连接参数配置不符合新版本驱动要求,才会出现提前告警但最终连接成功的情况:
db.js中存在两次mongoose.connect调用,第一次在函数外部没有传任何兼容参数,直接触发告警,第二次在connectDB内的配置才是正确的- 连接串里的
w=majority属于顶层写关注配置,新版本驱动要求统一放到writeConcern参数下 - server.js里端口打印的模板字符串用了单引号,导致变量不生效(属于附带小问题)
具体修改步骤
第一步:修正db.js的重复连接问题
删除db.js里const connectDB = async () => {上方多余的mongoose.connect(db),修改后的完整db.js代码如下:
//Bring in the libraries needed const mongoose = require('mongoose'); const config = require('config'); //get the mongoURI global variable from config package and save into variable called db const db = config.get('MONGO_URI'); //connect to mongoDB using async await promise arrow function const connectDB = async () => { try { //if try works await mongoose.connect(db, { useNewUrlParser: true, useCreateIndex: true, useFindAndModify: false, useUnifiedTopology: true, // 新增writeConcern配置,对应原连接串的w=majority参数 writeConcern: { w: 'majority' } }); console.log('Mongodb Connected...'); } catch(err){ //if try fails console.error(err.message); //exit process with failure process.exit(1); } } //allow file export module.exports = connectDB;
第二步:修改default.json连接串
删除连接串末尾的&w=majority参数,修改后的配置如下:
{ "MONGO_URI": "mongodb+srv://name:password@cluster0.9jhpi.mongodb.net/myFirstDatabase?retryWrites=true" }
第三步:修正server.js模板字符串语法
把app.listen回调内的单引号替换为反引号,正确解析端口变量:
app.listen(PORT, () => console.log(`Server Started on port ${PORT}`));
修改完成后重启服务即可消除全部告警,连接日志也会正常输出。
内容的提问来源于stack exchange,提问作者user5640752
相关产品推荐
相关产品推荐

