js中的代码如下所示,结果node.js运行时报错
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/playground')
.then(() => console.log('数据库连接成功'))
.catch(err => console.log(err, '数据库连接失败'))
错误提示:
(node:11540) 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:11540) 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 } 到 MongoClient. connect。
弃用警告:当前服务器发现和监视引擎已弃用,将在将来的版本中删除。要使用新的服务器发现和监视引擎,请将选项 { useUnifiedTopology: true } 传递给 MongoClient 构造函数。
也就是我们需要在代码块中写入这两条信息。
解决方案如下:
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/playground', { useNewUrlParser: true , useUnifiedTopology: true })
.then(() => console.log('数据库连接成功'))
.catch(err => console.log(err, '数据库连接失败'))
解决问题。
附:启动数据库和关闭数据库的命令
net start mongoDB //启动数据库服务
net stop mongoDB // 关闭数据库服务