New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

DeprecationWarning: `open()` is deprecated in mongoose >= 4.11.0, use `openUri()` instead #5399

Closed
cosminn777 opened this Issue Jun 25, 2017 · 158 comments

Comments

Projects
None yet
@cosminn777

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

Mongoose 4.11.0, MongoDB 2.2.29, NodeJS 8.1.2

@alanpurple

This comment has been minimized.

Show comment
Hide comment
@alanpurple

alanpurple Jun 25, 2017

+1 , I have no idea where to fix to get rid of that warning

alanpurple commented Jun 25, 2017

+1 , I have no idea where to fix to get rid of that warning

@tinovyatkin

This comment has been minimized.

Show comment
Hide comment
@tinovyatkin

tinovyatkin Jun 25, 2017

The warning is for a code inside Mongoose actually, when connecting string has a replica set:

Mongoose.prototype.connect = function() {
  var conn = this.connection;
  if ((arguments.length === 2 || arguments.length === 3) &&
      typeof arguments[0] === 'string' &&
      typeof arguments[1] === 'object' &&
      arguments[1].useMongoClient === true) {
    return conn.openUri(arguments[0], arguments[1], arguments[2]);
  }
  if (rgxReplSet.test(arguments[0]) || checkReplicaSetInUri(arguments[0])) {
    return new MongooseThenable(this, conn.openSet.apply(conn, arguments));
  }

  return new MongooseThenable(this, conn.open.apply(conn, arguments));
};

The warning is for a code inside Mongoose actually, when connecting string has a replica set:

Mongoose.prototype.connect = function() {
  var conn = this.connection;
  if ((arguments.length === 2 || arguments.length === 3) &&
      typeof arguments[0] === 'string' &&
      typeof arguments[1] === 'object' &&
      arguments[1].useMongoClient === true) {
    return conn.openUri(arguments[0], arguments[1], arguments[2]);
  }
  if (rgxReplSet.test(arguments[0]) || checkReplicaSetInUri(arguments[0])) {
    return new MongooseThenable(this, conn.openSet.apply(conn, arguments));
  }

  return new MongooseThenable(this, conn.open.apply(conn, arguments));
};
@alanpurple

This comment has been minimized.

Show comment
Hide comment
@alanpurple

alanpurple Jun 25, 2017

@tinovyatkin

So then, this is a bug?

@tinovyatkin

So then, this is a bug?

@tinovyatkin

This comment has been minimized.

Show comment
Hide comment
@tinovyatkin

tinovyatkin Jun 25, 2017

looks like a bug, can we workaround by adding useMongoClient: true to options (you may see a deprecation from MongoDB driver then but that doesn't throw)

tinovyatkin commented Jun 25, 2017

looks like a bug, can we workaround by adding useMongoClient: true to options (you may see a deprecation from MongoDB driver then but that doesn't throw)

@matthagemann

This comment has been minimized.

Show comment
Hide comment
@matthagemann

matthagemann Jun 25, 2017

Adding useMongoClient: true makes the message disappear, but then my documents simply stop loading. Haven’t debugged it deeper, but I would prefer to hear best practices first before I adapt my code.

Adding useMongoClient: true makes the message disappear, but then my documents simply stop loading. Haven’t debugged it deeper, but I would prefer to hear best practices first before I adapt my code.

@artnicbr

This comment has been minimized.

Show comment
Hide comment
@artnicbr

artnicbr Jun 25, 2017

My application also doesn't work with the workaround suggested above. It simply doesn't run MyModel.find method anymore and gives no error and no timeout.

My application also doesn't work with the workaround suggested above. It simply doesn't run MyModel.find method anymore and gives no error and no timeout.

@alanpurple

This comment has been minimized.

Show comment
Hide comment
@alanpurple

alanpurple Jun 25, 2017

The reason why "useMongoclient: true" option doesn't work for most of the cases is for that option, every mongoose connection-related object returns dummy object cause not able to access mongodb

I tried to use it like

const server = express();
mongoose.connect('mongodb://localhost/advisorDemoTestDB', { useMongoClient: true })
    .then(() => require('./db-init')(server))
    .catch(err => console.error(err));

but it doesn't work

alanpurple commented Jun 25, 2017

The reason why "useMongoclient: true" option doesn't work for most of the cases is for that option, every mongoose connection-related object returns dummy object cause not able to access mongodb

I tried to use it like

const server = express();
mongoose.connect('mongodb://localhost/advisorDemoTestDB', { useMongoClient: true })
    .then(() => require('./db-init')(server))
    .catch(err => console.error(err));

but it doesn't work

@JCMais

This comment has been minimized.

Show comment
Hide comment
@JCMais

JCMais Jun 25, 2017

Having same issue, even without replica sets.

JCMais commented Jun 25, 2017

Having same issue, even without replica sets.

@bertolo1988

This comment has been minimized.

Show comment
Hide comment
@bertolo1988

bertolo1988 Jun 25, 2017

Having same issue:

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

bertolo1988 commented Jun 25, 2017

Having same issue:

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

This comment has been minimized.

Show comment
Hide comment

DZuz14 commented Jun 26, 2017

Same...

@z1000zhihe

This comment has been minimized.

Show comment
Hide comment
@z1000zhihe

z1000zhihe Jun 26, 2017

After I added below code to my mongo connection, I can't query out anything now.
{useMongoClient: true}.
Any suggestions will be appreciate!!

After I added below code to my mongo connection, I can't query out anything now.
{useMongoClient: true}.
Any suggestions will be appreciate!!

@angeloLed

This comment has been minimized.

Show comment
Hide comment
@angeloLed

angeloLed Jun 26, 2017

+1 same with replica sets, no sharding

+1 same with replica sets, no sharding

@niftytushar

This comment has been minimized.

Show comment
Hide comment

+1

@evandersar

This comment has been minimized.

Show comment
Hide comment

+1

@prawee

This comment has been minimized.

Show comment
Hide comment

prawee commented Jun 26, 2017

+1

@Heartz66

This comment has been minimized.

Show comment
Hide comment

+1

@Yurockkk

This comment has been minimized.

Show comment
Hide comment

+1

@IoHL

This comment has been minimized.

Show comment
Hide comment

IoHL commented Jun 26, 2017

+1

@Math3v

This comment has been minimized.

Show comment
Hide comment

Math3v commented Jun 26, 2017

+1

@Chenz62

This comment has been minimized.

Show comment
Hide comment
@Chenz62

Chenz62 Jun 26, 2017

The easiest fix for this; "npm remove mongoose" then "npm install mongoose@4.10.8 --save" problem solved. Upgrading is not always the best option.

Chenz62 commented Jun 26, 2017

The easiest fix for this; "npm remove mongoose" then "npm install mongoose@4.10.8 --save" problem solved. Upgrading is not always the best option.

@toddmurphy

This comment has been minimized.

Show comment
Hide comment

+1

@Systerr

This comment has been minimized.

Show comment
Hide comment

Systerr commented Jun 26, 2017

+1

@plhosk

This comment has been minimized.

Show comment
Hide comment
@plhosk

plhosk Jun 26, 2017

I get 2 messages:

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

Server started on port 3000

Db.prototype.authenticate method will no longer be available in the next major
release 3.x as MongoDB 3.6 will only allow auth against users in the admin db
and will no longer allow multiple credentials on a socket. Please authenticate
using MongoClient.connect with auth credentials.

The first error appeared in 4.11.0. The second error also appeared in the previous version of Mongoose.

plhosk commented Jun 26, 2017

I get 2 messages:

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

Server started on port 3000

Db.prototype.authenticate method will no longer be available in the next major
release 3.x as MongoDB 3.6 will only allow auth against users in the admin db
and will no longer allow multiple credentials on a socket. Please authenticate
using MongoClient.connect with auth credentials.

The first error appeared in 4.11.0. The second error also appeared in the previous version of Mongoose.

@cosminn777

This comment has been minimized.

Show comment
Hide comment
@cosminn777

cosminn777 Jun 26, 2017

plhosk, the second one should have been fixed in 4.11 but looks like it's still there, for me too.

plhosk, the second one should have been fixed in 4.11 but looks like it's still there, for me too.

@jlobos

This comment has been minimized.

Show comment
Hide comment

jlobos commented Jun 26, 2017

+1

@Alhern

This comment has been minimized.

Show comment
Hide comment
@Alhern

Alhern Jun 26, 2017

+1 sadly.

Alhern commented Jun 26, 2017

+1 sadly.

@DellAnderson

This comment has been minimized.

Show comment
Hide comment
@DellAnderson

DellAnderson Jun 26, 2017

Installed 4.10.8 without issues. Please consider changing npm install mongoose --save to default to 4.10.8 until 11 is stable.

Installed 4.10.8 without issues. Please consider changing npm install mongoose --save to default to 4.10.8 until 11 is stable.

@nicholaai

This comment has been minimized.

Show comment
Hide comment

+1

@montoias

This comment has been minimized.

Show comment
Hide comment

+1

@NguyenManh94

This comment has been minimized.

Show comment
Hide comment

+1

@mattmengCooper

This comment has been minimized.

Show comment
Hide comment

+1

@itpcc

This comment has been minimized.

Show comment
Hide comment
@itpcc

itpcc Jun 27, 2017

I also found this issue too.
Node version: v6.10.0

MongoDB emvironment: (I ran on the latest version of Mongo docker container)

2017-06-20T08:04:24.509+0000 I CONTROL  [initandlisten] db version v3.4.5
2017-06-20T08:04:24.509+0000 I CONTROL  [initandlisten] git version: 520b8f3092c48d934f0cd78ab5f40fe594f96863
2017-06-20T08:04:24.509+0000 I CONTROL  [initandlisten] OpenSSL version: OpenSSL 1.0.1t  3 May 2016
2017-06-20T08:04:24.509+0000 I CONTROL  [initandlisten] allocator: tcmalloc
2017-06-20T08:04:24.509+0000 I CONTROL  [initandlisten] modules: none
2017-06-20T08:04:24.509+0000 I CONTROL  [initandlisten] build environment:
2017-06-20T08:04:24.509+0000 I CONTROL  [initandlisten]     distmod: debian81
2017-06-20T08:04:24.509+0000 I CONTROL  [initandlisten]     distarch: x86_64
2017-06-20T08:04:24.509+0000 I CONTROL  [initandlisten]     target_arch: x86_64
2017-06-20T08:04:24.509+0000 I CONTROL  [initandlisten] options: { security: { authorization: "enabled" } }

My connection configuration:

var dbURL = `mongodb://${dbHost}:${dbPort}/${dbName}?authSource=admin`;
var dbAuth = { 
	useMongoClient: false
	user: dbUser,
	pass: dbPass
}
mongoose.connect(dbURL, dbAuth);

When I use useMongoClient to be false. Mongoose show following warnings:

(node:7868) DeprecationWarning: `open()` is deprecated in mongoose >= 4.11.0, use `openUri()` instead, or set the `useMongoClient` option if using `connect()` or `createConnection()`
Express server listening on port 3222 in development mode
Db.prototype.authenticate method will no longer be available in the next major release 3.x as MongoDB 3.6 will only allow auth against users in the admin db and will no longer allow multiple credentials on a socket. Please authenticate u
sing MongoClient.connect with auth credentials.

But it work just fine.

However, when I set it to true, I found this error:

Unhandled rejection MongoError: not authorized on users to execute command { listIndexes: "sessions", cursor: {} }
    at Function.MongoError.create (<my project path>\node_modules\mongoose\node_modules\mongodb-core\lib\error.js:31:11)
    at queryCallback (<my project path>\node_modules\mongoose\node_modules\mongodb-core\lib\cursor.js:212:36)
    at <my project path>\node_modules\mongoose\node_modules\mongodb-core\lib\connection\pool.js:469:18
    at _combinedTickCallback (internal/process/next_tick.js:67:7)
    at process._tickCallback (internal/process/next_tick.js:98:9)

I also try to remove authSource=admin from connection URL too, but it still doesn't work

itpcc commented Jun 27, 2017

I also found this issue too.
Node version: v6.10.0

MongoDB emvironment: (I ran on the latest version of Mongo docker container)

2017-06-20T08:04:24.509+0000 I CONTROL  [initandlisten] db version v3.4.5
2017-06-20T08:04:24.509+0000 I CONTROL  [initandlisten] git version: 520b8f3092c48d934f0cd78ab5f40fe594f96863
2017-06-20T08:04:24.509+0000 I CONTROL  [initandlisten] OpenSSL version: OpenSSL 1.0.1t  3 May 2016
2017-06-20T08:04:24.509+0000 I CONTROL  [initandlisten] allocator: tcmalloc
2017-06-20T08:04:24.509+0000 I CONTROL  [initandlisten] modules: none
2017-06-20T08:04:24.509+0000 I CONTROL  [initandlisten] build environment:
2017-06-20T08:04:24.509+0000 I CONTROL  [initandlisten]     distmod: debian81
2017-06-20T08:04:24.509+0000 I CONTROL  [initandlisten]     distarch: x86_64
2017-06-20T08:04:24.509+0000 I CONTROL  [initandlisten]     target_arch: x86_64
2017-06-20T08:04:24.509+0000 I CONTROL  [initandlisten] options: { security: { authorization: "enabled" } }

My connection configuration:

var dbURL = `mongodb://${dbHost}:${dbPort}/${dbName}?authSource=admin`;
var dbAuth = { 
	useMongoClient: false
	user: dbUser,
	pass: dbPass
}
mongoose.connect(dbURL, dbAuth);

When I use useMongoClient to be false. Mongoose show following warnings:

(node:7868) DeprecationWarning: `open()` is deprecated in mongoose >= 4.11.0, use `openUri()` instead, or set the `useMongoClient` option if using `connect()` or `createConnection()`
Express server listening on port 3222 in development mode
Db.prototype.authenticate method will no longer be available in the next major release 3.x as MongoDB 3.6 will only allow auth against users in the admin db and will no longer allow multiple credentials on a socket. Please authenticate u
sing MongoClient.connect with auth credentials.

But it work just fine.

However, when I set it to true, I found this error:

Unhandled rejection MongoError: not authorized on users to execute command { listIndexes: "sessions", cursor: {} }
    at Function.MongoError.create (<my project path>\node_modules\mongoose\node_modules\mongodb-core\lib\error.js:31:11)
    at queryCallback (<my project path>\node_modules\mongoose\node_modules\mongodb-core\lib\cursor.js:212:36)
    at <my project path>\node_modules\mongoose\node_modules\mongodb-core\lib\connection\pool.js:469:18
    at _combinedTickCallback (internal/process/next_tick.js:67:7)
    at process._tickCallback (internal/process/next_tick.js:98:9)

I also try to remove authSource=admin from connection URL too, but it still doesn't work

@ajaymore

This comment has been minimized.

Show comment
Hide comment
@ajaymore

ajaymore Jun 27, 2017

(node:451) DeprecationWarning: open() is deprecated in mongoose >= 4.11.0, use
openUri() instead, or set the useMongoClient option if using connect() or createConnection()
Db.prototype.authenticate method will no longer be available in the next major re
lease 3.x as MongoDB 3.6 will only allow auth against users in the admin db and w
ill no longer allow multiple credentials on a socket. Please authenticate using M
ongoClient.connect with auth credentials.

I get this issue with mongoose version 4.11.0 and MongoDB version 3.4.5

(node:451) DeprecationWarning: open() is deprecated in mongoose >= 4.11.0, use
openUri() instead, or set the useMongoClient option if using connect() or createConnection()
Db.prototype.authenticate method will no longer be available in the next major re
lease 3.x as MongoDB 3.6 will only allow auth against users in the admin db and w
ill no longer allow multiple credentials on a socket. Please authenticate using M
ongoClient.connect with auth credentials.

I get this issue with mongoose version 4.11.0 and MongoDB version 3.4.5

@jcurlier

This comment has been minimized.

Show comment
Hide comment

+1

@jlanio

This comment has been minimized.

Show comment
Hide comment

jlanio commented Jun 27, 2017

+1

@nandofalcao

This comment has been minimized.

Show comment
Hide comment
@nandofalcao

nandofalcao Jun 27, 2017

Use

mongoose.createConnection(URI)

Use

mongoose.createConnection(URI)
@jlanio

This comment has been minimized.

Show comment
Hide comment
@jlanio

jlanio Jun 27, 2017

@nandofalcao When using:

  • mongoose.createConnection (URI);
  • mongoose.connect (URI, {useMongoClient: true});

Apparently I can not save new records.

let userSchema = mongoose.Schema({ name: String });
let User = mongoose.model('User', userSchema);
let joao = new User({ name: 'NewJoao ' });
joao.save((err) => err ? throw err : console.log('User created!'));//nothing happens

jlanio commented Jun 27, 2017

@nandofalcao When using:

  • mongoose.createConnection (URI);
  • mongoose.connect (URI, {useMongoClient: true});

Apparently I can not save new records.

let userSchema = mongoose.Schema({ name: String });
let User = mongoose.model('User', userSchema);
let joao = new User({ name: 'NewJoao ' });
joao.save((err) => err ? throw err : console.log('User created!'));//nothing happens
@amackintosh

This comment has been minimized.

Show comment
Hide comment
@amackintosh

amackintosh Jun 27, 2017

Adding polyglot tonight and +1 experiencing this.

// Load Mongoose
const mongoose = require('mongoose');
// import mongoose from 'mongoose' didn't give access to .connect()

// Use native Promises
mongoose.Promise = global.Promise;

// Connect database
export const Mongoose = new Promise((resolve, reject) => {
  const uri = `mongodb://${Singleton.currentConfig.databases.mongodb.host}/${Singleton.currentConfig.databases.mongodb.database}`;

  const options = {
    user: Singleton.currentConfig.databases.mongodb.user,
    pass: Singleton.currentConfig.databases.mongodb.password,
    server: {
      reconnectTries: Singleton.currentConfig.databases.mongodb.reconnectTries,
      reconnectInterval: Singleton.currentConfig.databases.mongodb.reconnectInterval,
      socketOptions: {
        keepAlive: Singleton.currentConfig.databases.mongodb.keepAlive,
        connectTimeoutMS: Singleton.currentConfig.databases.mongodb.connectTimeoutMS
      },
    },
  };

  // Initiate document store
  mongoose.connect(uri, options)

  // Check for anomalies
  .then((connected) => {
    if (mongoose.connection.readyState !== 1) {
      reject(connected);
    }
    resolve(connected);
  })

  // Complete meltdown
  .catch((error) => {
    console.log(`MongoDB Connection Error: ${error}`);
    process.exit(0);
  });
});

Adding polyglot tonight and +1 experiencing this.

// Load Mongoose
const mongoose = require('mongoose');
// import mongoose from 'mongoose' didn't give access to .connect()

// Use native Promises
mongoose.Promise = global.Promise;

// Connect database
export const Mongoose = new Promise((resolve, reject) => {
  const uri = `mongodb://${Singleton.currentConfig.databases.mongodb.host}/${Singleton.currentConfig.databases.mongodb.database}`;

  const options = {
    user: Singleton.currentConfig.databases.mongodb.user,
    pass: Singleton.currentConfig.databases.mongodb.password,
    server: {
      reconnectTries: Singleton.currentConfig.databases.mongodb.reconnectTries,
      reconnectInterval: Singleton.currentConfig.databases.mongodb.reconnectInterval,
      socketOptions: {
        keepAlive: Singleton.currentConfig.databases.mongodb.keepAlive,
        connectTimeoutMS: Singleton.currentConfig.databases.mongodb.connectTimeoutMS
      },
    },
  };

  // Initiate document store
  mongoose.connect(uri, options)

  // Check for anomalies
  .then((connected) => {
    if (mongoose.connection.readyState !== 1) {
      reject(connected);
    }
    resolve(connected);
  })

  // Complete meltdown
  .catch((error) => {
    console.log(`MongoDB Connection Error: ${error}`);
    process.exit(0);
  });
});

@shams-ali

This comment has been minimized.

Show comment
Hide comment
@shams-ali

shams-ali Aug 1, 2017

@iamdubx did you try my solution above? Could you paste the warning on this? Maybe I could help out :)

@iamdubx did you try my solution above? Could you paste the warning on this? Maybe I could help out :)

@FinalDes

This comment has been minimized.

Show comment
Hide comment
@FinalDes

FinalDes Aug 1, 2017

@iamdubx can post your warning message?

FinalDes commented Aug 1, 2017

@iamdubx can post your warning message?

@hackuun

This comment has been minimized.

Show comment
Hide comment
@hackuun

hackuun Aug 1, 2017

@FinalDes @shams-ali I posted before, it's the same deprecation error as topic has. The one this topic is about!

(node:3304) 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
Server listening on port: 7777
Db.prototype.authenticate method will no longer be available in the next major release 3.x as MongoDB 3.6 will only allow auth against users in the admin db and will no longer allow multiple credentials on a socket. Please authenticate using MongoClient.connect with auth credentials.

hackuun commented Aug 1, 2017

@FinalDes @shams-ali I posted before, it's the same deprecation error as topic has. The one this topic is about!

(node:3304) 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
Server listening on port: 7777
Db.prototype.authenticate method will no longer be available in the next major release 3.x as MongoDB 3.6 will only allow auth against users in the admin db and will no longer allow multiple credentials on a socket. Please authenticate using MongoClient.connect with auth credentials.

wilkmaia added a commit to wilkmaia/zssn-backend that referenced this issue Aug 1, 2017

Downgrade mongoose to 4.10.8
The version 4.11 introduces a change on the way mongoose connects to a
mongodb cluster. Some users are experiencing problems with the update
(Automattic/mongoose#5399) and are still not
able to remove the warning message upon initialization.

This commit downgrades Mongoose for the time being.
@shams-ali

This comment has been minimized.

Show comment
Hide comment
@shams-ali

shams-ali Aug 1, 2017

@iamdubx interesting, that's the same warning I had and the above solution I posted seemed to fix it for me. Could you paste your updated code that isn't working?

@iamdubx interesting, that's the same warning I had and the above solution I posted seemed to fix it for me. Could you paste your updated code that isn't working?

@0xnu

This comment has been minimized.

Show comment
Hide comment
@0xnu

0xnu Aug 2, 2017

This is what worked for me:

// ES6 promises
mongoose.Promise = Promise;

// mongodb connection
mongoose.connect("mongodb://localhost:27017/sandbox", {
  useMongoClient: true,
  promiseLibrary: global.Promise
});

var db = mongoose.connection;

// mongodb error
db.on('error', console.error.bind(console, 'connection error:'));

// mongodb connection open
db.once('open', () => {
  console.log(`Connected to Mongo at: ${new Date()}`)
});

0xnu commented Aug 2, 2017

This is what worked for me:

// ES6 promises
mongoose.Promise = Promise;

// mongodb connection
mongoose.connect("mongodb://localhost:27017/sandbox", {
  useMongoClient: true,
  promiseLibrary: global.Promise
});

var db = mongoose.connection;

// mongodb error
db.on('error', console.error.bind(console, 'connection error:'));

// mongodb connection open
db.once('open', () => {
  console.log(`Connected to Mongo at: ${new Date()}`)
});
@FinalDes

This comment has been minimized.

Show comment
Hide comment
@FinalDes

FinalDes Aug 3, 2017

@afoke is works thanks

FinalDes commented Aug 3, 2017

@afoke is works thanks

@0xnu

This comment has been minimized.

Show comment
Hide comment
@0xnu

0xnu Aug 3, 2017

@FinalDes You're welcome mate.

0xnu commented Aug 3, 2017

@FinalDes You're welcome mate.

@betafcc

This comment has been minimized.

Show comment
Hide comment
@betafcc

betafcc Aug 3, 2017

This is my new workflow, trying to be compliant with the warnings and deprecations:

// db.js
const model = require('./model');
const mongoose = require('mongoose');
mongoose.Promise = global.Promise;


async function db(uri) {
  const con = await mongoose
    .createConnection(uri, {
      useMongoClient: true,
    });

  const {User} = model(con);

  // do something with User
  ...

  // the interface for the server
  return {
    create: params => User.create(params),
    ...
  };
}


module.exports = db;

And now the models module returns a function of connection

// model.js
const {Schema} = require('mongoose');


const UserSchema = new Schema({
  name: String,
  age: Number,
});

// Other Schemas
...

module.exports = con => ({
  User: con.model('User', UserSchema),
  ...
});

Any official guidelines on the subject?

betafcc commented Aug 3, 2017

This is my new workflow, trying to be compliant with the warnings and deprecations:

// db.js
const model = require('./model');
const mongoose = require('mongoose');
mongoose.Promise = global.Promise;


async function db(uri) {
  const con = await mongoose
    .createConnection(uri, {
      useMongoClient: true,
    });

  const {User} = model(con);

  // do something with User
  ...

  // the interface for the server
  return {
    create: params => User.create(params),
    ...
  };
}


module.exports = db;

And now the models module returns a function of connection

// model.js
const {Schema} = require('mongoose');


const UserSchema = new Schema({
  name: String,
  age: Number,
});

// Other Schemas
...

module.exports = con => ({
  User: con.model('User', UserSchema),
  ...
});

Any official guidelines on the subject?

@chrisdothtml

This comment has been minimized.

Show comment
Hide comment
@chrisdothtml

chrisdothtml Aug 4, 2017

@iamdubx Sounds like you don't understand the difference between a warning and an error.

The warning in question does not break anything, but warns the user of something that will be removed in the next major release.

Mongoose is horrible.

So keep in mind, you're having this reaction to the developers warning you ahead of time before they remove a feature. I'd also urge you to remember that you're using this free of charge, so maybe give the developers the benefit of the doubt before you throw a tantrum

@iamdubx Sounds like you don't understand the difference between a warning and an error.

The warning in question does not break anything, but warns the user of something that will be removed in the next major release.

Mongoose is horrible.

So keep in mind, you're having this reaction to the developers warning you ahead of time before they remove a feature. I'd also urge you to remember that you're using this free of charge, so maybe give the developers the benefit of the doubt before you throw a tantrum

@bertolo1988

This comment has been minimized.

Show comment
Hide comment
@bertolo1988

bertolo1988 Aug 4, 2017

@chrisdothtml

The warning in question does not break anything, but warns the user of something that will be removed in the next major release.

It does pollute tests and console which is mildly annoying.

Mongoose is horrible. Also worst documentation site that I saw in libraries that so popular. What a shame!

He is being impolite which is also mildly annoying but he makes a very valid point in regards to Mongoose documentation. It is not the worst documentation ever but it could really be improved.

The fact that mongoose forwards the mongo client API. which works in a very different way, makes Mongoose usage and documentation confusing.

A possible solution for this would be:

  • stop doing it
  • remove the documentation for the Mongo client methods
  • provide a way to share connection between the official client and Mongoose

I would also suggest improving docs searchability by breaking it in several pages and giving more insight to new users about on what is Mongoose actually doing to achieve some of the results.

bertolo1988 commented Aug 4, 2017

@chrisdothtml

The warning in question does not break anything, but warns the user of something that will be removed in the next major release.

It does pollute tests and console which is mildly annoying.

Mongoose is horrible. Also worst documentation site that I saw in libraries that so popular. What a shame!

He is being impolite which is also mildly annoying but he makes a very valid point in regards to Mongoose documentation. It is not the worst documentation ever but it could really be improved.

The fact that mongoose forwards the mongo client API. which works in a very different way, makes Mongoose usage and documentation confusing.

A possible solution for this would be:

  • stop doing it
  • remove the documentation for the Mongo client methods
  • provide a way to share connection between the official client and Mongoose

I would also suggest improving docs searchability by breaking it in several pages and giving more insight to new users about on what is Mongoose actually doing to achieve some of the results.

@jameskentTX

This comment has been minimized.

Show comment
Hide comment
@jameskentTX

jameskentTX Aug 7, 2017

I had this error, but it disappeared after I added {useMongoClient: true} option.
I use Debian 9, testing version, with MongoDb ver. 3.2.11 and mongoose ver. 4.10.4.
I have 'Connected to MongoDB' message (view code in Typescript below), everything works perfectly.

(< any >mongoose).Promise = global.Promise;
mongoose.connect(process.env.MONGODB_URI, {useMongoClient: true});
const db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', () => {
console.log('Connected to MongoDB');
setRoutes(app);
app.get('/*', function(req, res) {
res.sendFile(path.join(__dirname, '../public/index.html'));
});
app.listen(app.get('port'), () => {
console.log('MyApp listening on port ' + app.get('port'));
});
});

jameskentTX commented Aug 7, 2017

I had this error, but it disappeared after I added {useMongoClient: true} option.
I use Debian 9, testing version, with MongoDb ver. 3.2.11 and mongoose ver. 4.10.4.
I have 'Connected to MongoDB' message (view code in Typescript below), everything works perfectly.

(< any >mongoose).Promise = global.Promise;
mongoose.connect(process.env.MONGODB_URI, {useMongoClient: true});
const db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', () => {
console.log('Connected to MongoDB');
setRoutes(app);
app.get('/*', function(req, res) {
res.sendFile(path.join(__dirname, '../public/index.html'));
});
app.listen(app.get('port'), () => {
console.log('MyApp listening on port ' + app.get('port'));
});
});

@karanpepi

This comment has been minimized.

Show comment
Hide comment
@karanpepi

karanpepi Aug 9, 2017

Just uninstall the current mongoose version which you have and install the lower version npm install mongoose@4.10.8 --save . No need to do anything else this will definately work for you.

Just uninstall the current mongoose version which you have and install the lower version npm install mongoose@4.10.8 --save . No need to do anything else this will definately work for you.

@systemsky

This comment has been minimized.

Show comment
Hide comment
@systemsky

systemsky Aug 13, 2017

mongoose.connect(database.host, { useMongoClient: true });

This solved my problem. But I had another warning coming up after I made this change.

DeprecationWarning: Mongoose: mpromise (mongoose's default promise library) is deprecated, plug in your own promise library instead: http://mongoosejs.com/docs/promises.html

systemsky commented Aug 13, 2017

mongoose.connect(database.host, { useMongoClient: true });

This solved my problem. But I had another warning coming up after I made this change.

DeprecationWarning: Mongoose: mpromise (mongoose's default promise library) is deprecated, plug in your own promise library instead: http://mongoosejs.com/docs/promises.html

@bricss

This comment has been minimized.

Show comment
Hide comment
@bricss

bricss Aug 13, 2017

This code solves all deprecation warnings:

mongoose.Promise = global.Promise;
mongoose.connect(uri, {
  keepAlive: true,
  reconnectTries: Number.MAX_VALUE,
  useMongoClient: true
});

More info by the link -> http://mongoosejs.com/docs/connections.html#use-mongo-client

bricss commented Aug 13, 2017

This code solves all deprecation warnings:

mongoose.Promise = global.Promise;
mongoose.connect(uri, {
  keepAlive: true,
  reconnectTries: Number.MAX_VALUE,
  useMongoClient: true
});

More info by the link -> http://mongoosejs.com/docs/connections.html#use-mongo-client

@artnicbr

This comment has been minimized.

Show comment
Hide comment
@artnicbr

artnicbr Aug 15, 2017

@bricss Fantastic! Thanks!

@bricss Fantastic! Thanks!

@kranz

This comment has been minimized.

Show comment
Hide comment
@kranz

kranz Aug 15, 2017

@bricss You made my day.

kranz commented Aug 15, 2017

@bricss You made my day.

@jpetitte

This comment has been minimized.

Show comment
Hide comment
@jpetitte

jpetitte Aug 15, 2017

someone earned a hero badge...

edit: @bricss It eliminated the deprecation warnings for me, but I couldn't retrieve data from my mLab sandboxes. It may be because they are using an older version of MongoDB. I'll try to check into it later.

edit: @bricss It's now working correctly with the latest mongoose 4.11.9 and a connection to Cosmos DB on Azure.

jpetitte commented Aug 15, 2017

someone earned a hero badge...

edit: @bricss It eliminated the deprecation warnings for me, but I couldn't retrieve data from my mLab sandboxes. It may be because they are using an older version of MongoDB. I'll try to check into it later.

edit: @bricss It's now working correctly with the latest mongoose 4.11.9 and a connection to Cosmos DB on Azure.

@systemsky

This comment has been minimized.

Show comment
Hide comment
@systemsky

systemsky Aug 16, 2017

@bricss : Nicely done Bricks! It worked for me even though I'm using a really old version of mongodb in my local 👍

@bricss : Nicely done Bricks! It worked for me even though I'm using a really old version of mongodb in my local 👍

@CodebyOmar

This comment has been minimized.

Show comment
Hide comment
@CodebyOmar

CodebyOmar Aug 16, 2017

@bricss Awesowe! But you might consider putting a smaller number for "reconnectTries". You don't want to spend the whole day reconnecting if there is an issue with your DB.

@bricss Awesowe! But you might consider putting a smaller number for "reconnectTries". You don't want to spend the whole day reconnecting if there is an issue with your DB.

@nikkwong

This comment has been minimized.

Show comment
Hide comment
@nikkwong

nikkwong Aug 19, 2017

@afoke 's solution worked for me, only when i explicitly declare the db in the connection string i.e. mongodb://localhost:27017/test but not mongodb://localhost:27017

@afoke 's solution worked for me, only when i explicitly declare the db in the connection string i.e. mongodb://localhost:27017/test but not mongodb://localhost:27017

@aprisniak

This comment has been minimized.

Show comment
Hide comment
@aprisniak

aprisniak Aug 21, 2017

May I create connection to 2 DB's without this warning? I need to use my models with different DB's.

May I create connection to 2 DB's without this warning? I need to use my models with different DB's.

nip10 added a commit to nip10/todo-api that referenced this issue Aug 24, 2017

Fixed mongoose config file
Node was throwing a deprecation error related to mongoose. This is a known bug (Automattic/mongoose#5399) so I used a work-around to avoid it.
@moolsbytheway

This comment has been minimized.

Show comment
Hide comment
@moolsbytheway

moolsbytheway Aug 27, 2017

Using mongoose v^4.11.6 , when added useMongoClient the warning dispeared.

const uri = "http://blablabla.blo/blaDB"; mongoose.Promise = global.Promise; mongoose.connection.on('error', (err) => { console.error(Mongoose connection error: ${err}`);
process.exit(1);
});
mongoose.connect(uri, {useMongoClient: true});

 // load models
 require('./model1');
 // ...
 require('./modelN');`

moolsbytheway commented Aug 27, 2017

Using mongoose v^4.11.6 , when added useMongoClient the warning dispeared.

const uri = "http://blablabla.blo/blaDB"; mongoose.Promise = global.Promise; mongoose.connection.on('error', (err) => { console.error(Mongoose connection error: ${err}`);
process.exit(1);
});
mongoose.connect(uri, {useMongoClient: true});

 // load models
 require('./model1');
 // ...
 require('./modelN');`

yagisuke added a commit to yagisuke/GraphQL that referenced this issue Sep 4, 2017

leonardosarmentocastro added a commit to leonardosarmentocastro/affinitas_editable_profile_backend that referenced this issue Sep 4, 2017

Mongoose - Fixed deprecated options
Details
. The latest version of "mongoose" package is having issues opening connections.
The following thread explains the problem and some users provided a workaround for it:
Automattic/mongoose#5399
@amado-saladino

This comment has been minimized.

Show comment
Hide comment
@amado-saladino

amado-saladino Sep 15, 2017

connecting to database in this way solves the problem:
mongoose.connect(url,{user:'username',pass:'mypassword',useMongoClient:true});

connecting to database in this way solves the problem:
mongoose.connect(url,{user:'username',pass:'mypassword',useMongoClient:true});

@iroshanAV

This comment has been minimized.

Show comment
Hide comment
@iroshanAV

iroshanAV Sep 17, 2017

Will these errors cause problems , for example in security?

Will these errors cause problems , for example in security?

@RxAssim

This comment has been minimized.

Show comment
Hide comment
@RxAssim

RxAssim Sep 17, 2017

No more "deprecated" warning pops up if I use this syntax 🎉

mongoose.connection.openUri('mongodb://localhost/test')
  .once('open', () => console.log('Good to go !'))
  .on('error', (error) => {
    console.warn('Warning', error);
  });

RxAssim commented Sep 17, 2017

No more "deprecated" warning pops up if I use this syntax 🎉

mongoose.connection.openUri('mongodb://localhost/test')
  .once('open', () => console.log('Good to go !'))
  .on('error', (error) => {
    console.warn('Warning', error);
  });
@mitesh-solulab

This comment has been minimized.

Show comment
Hide comment
@mitesh-solulab

mitesh-solulab Sep 21, 2017

I faced the same deprecation warning as below:
(node:2300) 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

Solution

I tried the following and it works fine. Gives no deprecation warnings.

mongoose.connect('mongodb://127.0.0.1:27017/your-database-name', { useMongoClient: true, promiseLibrary: global.Promise });

Hope this will help everyone facing this issue.

I faced the same deprecation warning as below:
(node:2300) 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

Solution

I tried the following and it works fine. Gives no deprecation warnings.

mongoose.connect('mongodb://127.0.0.1:27017/your-database-name', { useMongoClient: true, promiseLibrary: global.Promise });

Hope this will help everyone facing this issue.

@MichFe

This comment has been minimized.

Show comment
Hide comment
@MichFe

MichFe Sep 23, 2017

I have the same issue but when trying to connect to Mongo Atlas service it just not connect with {useMongoClient:true} option and without it the connection is no longer executed.

Anyone with the same issue?

MichFe commented Sep 23, 2017

I have the same issue but when trying to connect to Mongo Atlas service it just not connect with {useMongoClient:true} option and without it the connection is no longer executed.

Anyone with the same issue?

@mominbutt12

This comment has been minimized.

Show comment
Hide comment
@mominbutt12

mominbutt12 Oct 1, 2017

I had solved my problem by just change the mongoose.connect to mongoose.createConnection

mongoose.createConnection(config.uri, (err) => {
if (err) {
console.log('Could NOT connect to database: ', err);
} else {
console.log('Connected to database: ' + config.db);
}
});

I had solved my problem by just change the mongoose.connect to mongoose.createConnection

mongoose.createConnection(config.uri, (err) => {
if (err) {
console.log('Could NOT connect to database: ', err);
} else {
console.log('Connected to database: ' + config.db);
}
});

@stanisdev

This comment has been minimized.

Show comment
Hide comment
@stanisdev

stanisdev Oct 6, 2017

I solved this problem like that (Mongoose 4.12.0, NodeJS - 7.10.1)

mongoose.Promise = require('bluebird');
mongoose.connect('mongodb://localhost:27017/books_exchange', {
  useMongoClient: true,
  promiseLibrary: require('bluebird')
}).then(() => {
  var userSchema = new mongoose.Schema({
    name: String,
    password: String
  });
  var User = mongoose.model('User', userSchema);

  var person = new User({
    name: "John",
    password: "qwerty"
  });

  person.save().then(() => {
    console.log('Data saved');
  }).catch(e => {
    console.log(e);
  });
}).catch(e => {
  console.log('Error while DB connecting');
  console.log(e);
});

stanisdev commented Oct 6, 2017

I solved this problem like that (Mongoose 4.12.0, NodeJS - 7.10.1)

mongoose.Promise = require('bluebird');
mongoose.connect('mongodb://localhost:27017/books_exchange', {
  useMongoClient: true,
  promiseLibrary: require('bluebird')
}).then(() => {
  var userSchema = new mongoose.Schema({
    name: String,
    password: String
  });
  var User = mongoose.model('User', userSchema);

  var person = new User({
    name: "John",
    password: "qwerty"
  });

  person.save().then(() => {
    console.log('Data saved');
  }).catch(e => {
    console.log(e);
  });
}).catch(e => {
  console.log('Error while DB connecting');
  console.log(e);
});

@Automattic Automattic locked and limited conversation to collaborators Oct 6, 2017

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.