当前位置: 代码迷 >> 综合 >> Mongoose 4.11 开始的问题 useMongoClient
  详细解决方案

Mongoose 4.11 开始的问题 useMongoClient

热度:35   发布时间:2023-11-11 02:00:25.0

在打开mongoose时发现一个报错问题
DeprecationWarning: open() is deprecated in mongoose >= 4.11.0, use openUri() instead, or set the useMongoClient option if using connect() or createConnection(). See http://mongoosejs.com/docs/connections.html#use-mongo-client
opened

这上面虽然指出了解决问题的方法,但为什么要这样做呢?

于是google一下,果然找出了答案

This warning comes from the MongoDB Node.js driver. Currently, connecting and authenticating are distinct operations in MongoDB. You can connect to your database and then authenticate later, which is what mongoose 4.x does by default. You can even authenticate as multiple different users on the same connection.

As far as I understand, MongoDB is planning on removing this functionality in 3.6 and consolidating connecting and authenticating into one single operation. Keep in mind that I am not currently a MongoDB employee and do not speak for the company as a whole, my interpretation of this may not be entirely correct.

However, my understanding is that mongoose will not be able to authenticate against MongoDB 3.6 without the useMongoClient option. At the time of this writing, the release date for MongoDB 3.6 has not been announced yet. But I recommend you upgrade to mongoose 4.11 and start using useMongoClient as soon as possible, because to the best of my knowledge you will be able to use MongoDB 3.6 without it.

First, it’s important to note that useMongoClient only affects initial connection. Once you have successfully connected to MongoDB, your code should not have to do anything differently. If this is not the case, please report a bug on the mongoose GitHub page.

Secondly, as long as you’re using mongoose 4.x and you’re using MongoDB 3.4 or earlier, your existing connection code will continue to work. You will see the deprecation warning, but mongoose is committed to following semver, so you can safely ignore this warning until mongoose 5.x and MongoDB 3.6 are released and you choose to upgrade.

The useMongoClient option is for mongoose.connect() and mongoose.createConnection(). If you use mongoose.connect(), you don’t have to change much:

下面讲的是createConnection,老生常谈:

The createConnection() also works similarly. The difference is that, with mongoose >= 4.11.2 (but not 4.11.0 or 4.11.1 because of a bug) you can start using the returned connection object. You can optionally await on the returned connection to wait for initial connection.

结尾建议

The useMongoClient option is a big change, but a necessary one for mongoose to support MongoDB 3.6. MongoDB 3.6 has no scheduled release date yet, so switching is not pressing. However, I recommend you start using useMongoClient as soon as possible

原网址: http://thecodebarbarian.com/mongoose-4.11-use-mongo-client.html