Kalpesh Kashyap
Kalpesh Kashyap

Reputation: 824

DeprecationWarning: `ensureIndex()` is deprecated in Mongoose >= 4.12.0, use `createIndex()` instead

hello I have created node application it was working good but from last 2 days I got this error I have tried to upgrade mongoose but still same error

DeprecationWarning: ensureIndex() is deprecated in Mongoose >= 4.12.0, use createIndex() instead

because of this my application has stopped working

here my code to connect with mongodb

mongoose.connect(config.mongo.uri, {useMongoClient: true});
  mongoose.connection.on('error', function (err) {
  console.error(`MongoDB connection error: ${err}`);
  process.exit(-1); // eslint-disable-line no-process-exit 
 });

does anyone have solution of this , thanx in advance.

Upvotes: 1

Views: 5260

Answers (5)

reza babakhani
reza babakhani

Reputation: 89

You can add this code block on your connection:

mongoose.set("useCreateIndex", true);

That will fix your problem. I used it like this:

import mongoose from "mongoose";
mongoose.connect(`mongodb://localhost:27017/shopping`, {
    useUnifiedTopology: true,
    useNewUrlParser: true
  })
  .then(() => {
    console.log("connection to mongodb successful ...");
  })
  .catch(error =>
    console.log(`there is something wrong on mongoDB connection : ${error}`)
  );

mongoose.set("useCreateIndex", true);

Upvotes: 3

user3816703
user3816703

Reputation: 129

I finally solved this quite simply by following the official mongoose docs .

Basically there is a flag to pass through the connection options as follows:

mongoose.connect(dbconfig.database, {
    useCreateIndex: true
});

And this removed the deprecation warning message without having to modify my code any further.

Upvotes: 10

Codedreamer
Codedreamer

Reputation: 1702

Following the Mongodb docs. You have to disable autoIndex: false, then call the User createIndexes function. You need to configure your Schema like this.


account_type: {
        type: Number,
        default: config.accountType.admin
    },
    account_status: {
        type: Number,
        default: config.accountStatus.unVerified
    },
    socket_id: String,
    picture_url: {
        type: String
    }
},{
    timestamps: true,
    autoIndex: false
});

const User = mongoose.model('User', userSchema);

User.createIndexes();

// export model
module.exports = User;


Upvotes: 0

Kalpesh Kashyap
Kalpesh Kashyap

Reputation: 824

I have upgrade mongoose version to 4.9.9 and now I am not getting any warnning

Upvotes: 0

Jijo Paulose
Jijo Paulose

Reputation: 1956

MongoStore causes this notice.Please upgrade connect-mongo

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

npm i [email protected] --save

Upvotes: 3

Related Questions