【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"的版本也是可以的。?


版权声明:本文为weixin_40817115原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。