node.js 如何设置 useMongoClient (Mongoose 4.11.0)?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44749700/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 18:19:18  来源:igfitidea点击:

How to set useMongoClient (Mongoose 4.11.0)?

node.jsmongodbmongoose

提问by Tiago Bértolo

This is the code I use to connect to my database:

这是我用来连接到我的数据库的代码:

private connectDatabase(databaseUri: string): Promise<Mongoose.Connection> {
    return Mongoose.connect(databaseUri).then(() => {
        debug('Connected to MongoDB at %O', databaseUri);
        return Mongoose.connection;
    });
}

Today I updated Mongoose to version 4.11.0 and I got this warning when running my tests:

今天,我将 Mongoose 更新到了 4.11.0 版,并且在运行测试时收到了这个警告:

(node:4138) DeprecationWarning: `open()` is deprecated in mongoose >= 4.11.0,
use `openUri()` instead, or set the `useMongoClient` option if using `connect()`
or `createConnection()`

I can't find any information on how to "set useMongoClient".

我找不到有关如何“设置 useMongoClient”的任何信息。

Do you guys know how to?

大家知道怎么做吗?

采纳答案by Tiago Bértolo

Without Typescriptyou can pretty much ignore the issue and use Mongoose.connect(databaseUri, { useMongoClient: true }).

如果没有打字稿,您几乎可以忽略该问题并使用Mongoose.connect(databaseUri, { useMongoClient: true }).

If you really want to avoid having the warning avoid the version 4.11.0.

如果您真的想避免出现警告,请避免使用 4.11.0 版。

I updated to version 4.11.1 and since @types/[email protected] are not yet updated and they do not mention the field useMongoClientin the ConnectionOptions, this is how i imported the module:

我更新到4.11.1版本,因为@类型/猫鼬@尚未进行更新4.7.18和他们不提现场useMongoClientConnectionOptions,我这是怎么导入模块:

const Mongoose = require('mongoose');

And then used this function:

然后使用了这个函数:

private connectDatabase(databaseUri: string): Promise<any> {
    return Mongoose.connect(databaseUri, { useMongoClient: true })
        .then(() => {
            console.log('Connected to MongoDB at ', databaseUri);
            return Mongoose.connection;
        })
        .catch(err => debug(`Database connection error: ${err.message}`));
}

回答by Xertz

This is how you use useMongoClient:

这是你如何使用useMongoClient

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

回答by jan basha

Add { useMongoClient: true }as another argument to connect or createConnection method, its depends on version of mongoose you are using.

添加{ useMongoClient: true }作为 connect 或 createConnection 方法的另一个参数,这取决于您使用的猫鼬版本。

// Using `mongoose.connect`...
var promise = mongoose.connect('mongodb://localhost/myapp', {
  useMongoClient: true,
  /* other options */
});
// Or `createConnection`
var promise = mongoose.createConnection('mongodb://localhost/myapp', {
  useMongoClient: true,
  /* other options */
});

回答by Crisam De gracia

mongoose.connection.openUri('mongodb://127.0.0.1/camp_v12')

has anyone tried this? my deprecated warning disappeared when i use this, it was from the documentation

有没有人试过这个?当我使用它时,我不推荐使用的警告消失了,它来自文档

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

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

回答by yogesh chatrola

The easiest fix for this would be to open your terminal, change your directory to your root project (folder where package.jsonis)

最简单的解决方法是打开终端,将目录更改为根项目(所在文件夹package.json

Run:
npm remove mongoose

跑:
npm remove mongoose

then:

然后:

npm install [email protected] --save

npm install [email protected] --save

problem solved.

问题解决了。

Upgrading is not always the best option.

升级并不总是最好的选择。

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

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

回答by Abhishek Gupta

As many answers say, adding { useMongoClient: true }in options argument to connector createConnectionmethod will solve the problem.

正如许多答案所说,{ useMongoClient: true }在选项参数connectcreateConnection方法中添加将解决问题。

For e.g.

例如

// With mongoose.connect method
mongoose.connect('mongodb://localhost/app', { useMongoClient: true });

// With createConnection method
mongoose.createConnection('mongodb://localhost/app', { useMongoClient: true });

But what is MongoClient in the first place?

但是首先什么是 MongoClient ?

From MongoDB Node.js Driver version 1.2, a new connection class MongoClient was introduced that has the same name across all the official drivers.

从 MongoDB Node.js Driver version 1.2 开始,引入了一个新的连接类 MongoClient,它在所有官方驱动程序中都具有相同的名称。

The new connection class MongoClient acknowledges all writes to MongoDB, in contrast to the existing DB connection class which has acknowledgements turned off.

新的连接类MongoClient 确认所有写入 MongoDB,与关闭确认的现有数据库连接类形成对比。

So { useMongoClient: true }tells moongoose to use the new connection class rather than the old one

所以{ useMongoClient: true }告诉 Moongoose 使用新的连接类而不是旧的

For more info click here

欲了解更多信息,请单击此处

回答by krl

Connect to MongoDB with Mongoose 4.11.x (tested with both mLab single instance and MongoDB Atlas replica set):

使用 Mongoose 4.11.x 连接到 MongoDB(使用 mLab 单实例和 MongoDB Atlas 副本集测试):

const mongoose = require('mongoose');

mongoose.Promise = global.Promise;

const options = {
  promiseLibrary: global.Promise,
  useMongoClient: true,
};

function connect() {
  mongoose.connect(URI, options)
    .then(function() {
      const admin = new mongoose.mongo.Admin(mongoose.connection.db);
      admin.buildInfo(function(err, info) {
        if (err) {
          console.err(`Error getting MongoDB info: ${err}`);
        } else {
          console.log(`Connection to MongoDB (version ${info.version}) opened successfully!`);
        }
      });
    })
    .catch((err) => console.error(`Error connecting to MongoDB: ${err}`));
}

module.exports = connect;

Create model:

创建模型:

const mongoose = require('mongoose');

const userSchema = new mongoose.Schema({...});

module.exports = mongoose.model('User', userSchema);

回答by James Choi

According to the mongoosedocumentation, this is how useMongoClientcan be set.

根据mongoose文档,这是如何useMongoClient设置的。

function connectDatabase(databaseUri){
    var promise = mongoose.connect('mongodb://localhost/myapp', {
        useMongoClient: true,
    });
    return promise;
}

回答by Raja Parivesh

The easiest fix for this:

最简单的解决方法:

Run this command in project root folder via terminal:

通过终端在项目根文件夹中运行此命令:

npm remove mongoose

npm remove mongoose

npm install [email protected] --save

npm install [email protected] --save

Problem solved.

问题解决了。

Upgrading is not always the best option.

升级并不总是最好的选择。

https://github.com/Automattic/mongoose/issues/5399

https://github.com/Automattic/mongoose/issues/5399

回答by Aditya Parmar

var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/starbucks', { 
    useMongoClient: true 
});
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('openUri', function() {
    // we're connected!
});