mongoose警告「DeprecationWarning: current Server Discovery and Monitoring engine is deprecated…」を消す

mongoose警告「DeprecationWarning: current Server Discovery and Monitoring engine is deprecated…」を消す

node.jsのライブラリmongooseでmongodbに接続時にでる警告「DeprecationWarning: current Server Discovery and Monitoring engine is deprecated, and will be removed in a futur Discover and Monitoring engine, pass option { useUnifiedTopology: true } to the MongoClient constructor.」 を削除する手順を記述してます。

環境

  • OS  Ubuntu 20.10
  • node V14.15.1
  • npm 6.14.9
  • mongo 4.4.2
  • mongoose 5.11.0

警告全文

以下のコードを実行時に発生。

const mongoose = require('mongoose');

mongoose.connect('mongodb://127.0.0.1/hogedb')
    .then(() => console.log('接続ok'))
    .catch((err)=> console.error(err));

警告全文

DeprecationWarning: current Server Discovery and Monitoring engine is deprecated, and will be removed in a futur Discover and Monitoring engine, pass option { useUnifiedTopology: true } to the MongoClient constructor.

警告削除

言われた通りにオプションに指定します。

const mongoose = require('mongoose');

const options = {
	useUnifiedTopology : true
}

mongoose.connect('mongodb://127.0.0.1/sampledb',options)
    .then(() => console.log('connected'))
    .catch((err)=> console.error(err));

今度は、「{ useNewUrlParser: true }」がないと言われるので、

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

以下のように、追加します。

const mongoose = require('mongoose');

const options = {
	useUnifiedTopology : true,
	useNewUrlParser : true
}

mongoose.connect('mongodb://127.0.0.1/sampledb',options)
    .then(() => console.log('connected'))
    .catch((err)=> console.error(err));

これで警告は消えます。