DEV Community

Cui Mingda
Cui Mingda

Posted on

How to connect mongoDB server with useUnifiedTopology

基本指令就是connect命令

const mongoose = require('mongoose')
const mongoDB = 'mongodb://localhost:27017/learn'
mongoose.connect(mongoDB)
Enter fullscreen mode Exit fullscreen mode

遇到的第一个警告

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.
Enter fullscreen mode Exit fullscreen mode

遇到的第二个警告

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.
Enter fullscreen mode Exit fullscreen mode

上面两个警告,提示中已经给出了明确的解决方案,但是当设置了{ useUnifiedTopology: true }以后,会发现连接失败的时候,比如docker没有启动,也不会报异常。

原来useUnifiedTopology这个模式,会设置一个30秒的搜寻服务器的超时时间,就算服务器无法连接,也要等到超时以后才报错。解决方案就是通过设置serverSelectionTimeoutMS参数来解决。

最后的方案

mongoose.connect(mongoDB, {
  useNewUrlParser: true,
  serverSelectionTimeoutMS: 3000,
  useUnifiedTopology: true
}).then(() => {
  console.log('connect succeed')
}).catch((error) => {
  if (error.constructor.name === 'MongooseServerSelectionError') {
    console.error('Can not connect mongoDB server.')
  } else {
    console.log(error)
  }
})
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
divide_r_conquer profile image
Yuehui Ruan

这是什么语言呢?