【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. 方法一
  • 按照warning中给出的方案,在connect中添加option { useNewUrlParser: true }
    【mongoose链接mongodb】current URL string parser is deprecated, and will be removed in a future version_第1张图片添加option后,仍然没有connect success的log。
    原因:
    我使用的是mongoose:5.6.2,根据官方文档: https://mongoosejs.com/docs/给出的示例代码,
// 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"的版本也是可以的。?

你可能感兴趣的:(nodejs,mongoDB)