关于mongoose 连接警告报错信息处理

前言

今天在根据mongoose中文文档链接数据库时候,发现报了2个错误,百度查了一下,使用connect连接数据库时候必须配置{useNewUrlParser:true,useUnifiedTopology: true}

问题

const mongoose = require('mongoose');
const db= mongoose.connection;
const dbAddress='mongodb://localhost/douban';
mongoose.Promise=global.Promise
exports.connect=()=>{
    if(process.env.NODE_ENV !=='production'){
        mongoose.set('debug',true);
    }
    mongoose.connect(dbAddress);
    db.once('open',()=>{
        console.log('mongodb connect successly')
    });
    db.on('error',err=>{
        console.log(err);
    });
}
//(node:3960) DeprecationWarning: current URL string parser is deprecated, and will be removed in a future version. To use the new parser, pass option { useNewUrlParser: true } to MongoClient.connect.
//(node:3960) DeprecationWarning: current Server Discovery and Monitoring engine is deprecated, and will be removed in a future version. To use the new Server Discover and Monitoring engine, pass option { useUnifiedTopology: true } to the MongoClient constructor.  

解决方案:

const mongoose = require('mongoose');
const db= mongoose.connection;
const dbAddress='mongodb://localhost/douban';
mongoose.Promise=global.Promise
exports.connect=()=>{
    if(process.env.NODE_ENV !=='production'){
        mongoose.set('debug',true);
    }
    mongoose.connect(dbAddress, {useNewUrlParser:true,useUnifiedTopology: true});
    db.once('open',()=>{
        console.log('mongodb connect successly')
    });
    db.on('error',err=>{
        console.log(err);
    });
}

总结

看来还是看官方文档最靠谱,中文文档更新有些迟缓了。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容