nodejs连接MongoDB报错node:831解决方式

node.js连接mongodb,报错:

代码如下:

1 const mongoose = require('mongoose');
2 
3 mongoose.connect('mongodb://localhost/pg' )
4     .then(()=>console.log('数据库连接成功'))
5     .catch((err)=> console.log(err,'数据库连接失败'))

报错:

(node:831) 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:831) 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.

原因:不建议使用当前的URL字符串解析器,并将在以后的版本中将其删除。 要使用新的解析器,所以需要将这两个字段传入。 { useNewUrlParser: true }, { useUnifiedTopology: true } 

解决方式:

const mongoose = require('mongoose');

mongoose.connect('mongodb://localhost/pg',{useNewUrlParser: true , useUnifiedTopology: true } )
    .then(()=>console.log('数据库连接成功'))
    .catch((err)=> console.log(err,'数据库连接失败'))

将两个字段加到connect中即可。

 

 

posted @ 2020-11-12 01:00  菠菜猫  阅读(456)  评论(0编辑  收藏  举报