DeprecationWarning:`open()`在mongoose> = 4.11.0中弃用,改为使用`openUri()`,或者设置`useMongoClient`

时间:2018-02-26 03:41:20

标签: node.js mongodb

我在Node.js项目中使用MongoDB,当我在项目中运行node app.js时出现了类似下面的问题:

  

弃用警告:open()在mongoose> = 4.11.0中已弃用,请改用openUri(),或者如果使用useMongoClientconnect()则设置createConnection()选项}

我的核心代码:

var mongoose = require('mongoose')
mongoose.connect('mongodb://localhost/test');
var db = mongoose.connection

db.on('error', console.error.bind(console, 'connect error:'));
db.once('open', function() {
    console.log('connect success');
})

2 个答案:

答案 0 :(得分:1)

来自http://mongoosejs.com/docs/connections.html

const options = {
  useMongoClient: true,
  autoIndex: false, // Don't build indexes
  reconnectTries: Number.MAX_VALUE, // Never stop trying to reconnect
  reconnectInterval: 500, // Reconnect every 500ms
  poolSize: 10, // Maintain up to 10 socket connections
  // If not connected, return errors immediately rather than waiting for reconnect
  bufferMaxEntries: 0
};
mongoose.connect(uri, options);

连接mongodb时,应添加{useMongoClient:true}

mongoose.connect('mongodb://localhost/test',{useMongoClient:true})

答案 1 :(得分:0)

我也面临类似的错误。 解决方案:我将版本从 mongoose@4 更新为 mongoose5 。升级mongoose版本后问题解决。您可以应用我的解决方案,它可能有助于解决您的问题。

我如何更新我的猫鼬版本: 首先 goto npm mongoose official website 复制最新版本的猫鼬(我当时的最新版本是 5.12.13)。并使用 mongoose 版本模块粘贴 package.json 文件并运行 npm install 。安装所有包后。我使用 run index.js 运行我的应用程序,问题解决了。希望我的建议能帮到你。