【mongoose鏈接mongodb】current URL string parser is deprecated, and will be removed in a future version

一、 背景

使用mongoose鏈接mongoDB報warning:

(node:16780) 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 express = require('express');
const mongoose = require('mongoose');

// 鏈接mongo
const DB_URL = 'mongodb://127.0.0.1:27017/imooc';
mongoose.connect(DB_URL);
mongoose.connection.on('connected', ()=>console.log('mongo connect success'));

二、 解決方法

1. 方法一
// getting-started.js
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test', {useNewUrlParser: true});
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
  // we're connected!
});
  • mongoose.connection.on('connected', ()=>console.log('mongo connect success'));
    改爲mongoose.connection.once('open', ()=>console.log('mongo connect success'));
Server is listening 9093
mongodb connect success

連接數據庫成功。

2. 方法二

回退使用"mongoose": "^5.5.11"的版本也是可以的。😃

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章