skip to Main Content

I got error "throw new MongooseError(‘Mongoose.prototype.connect() no longer accepts a callback’);"


const mogoURI = "mongodb://localhost:27017/?directConnection=true";

const connectToMongo = ()=>{
    mongoose.connect(mogoURI,()=>{
        console.log("Connected to Mongo Successfully");
    })



}

module.exports = connectToMongo;```

3

Answers


  1. what version of mongoose are you using? As the error says the connect method does not take a callback function. The second argument to the function is now an options object you can pass, but now the third parameter is the callback function.

    doc: https://mongoosejs.com/docs/connections.html#callback

    in your case if you just remove that callback it should work, just do:

    mongoose.connect(mogoURI)

    Login or Signup to reply.
  2. As the error tells you, the callback is not supported anymore in Mongoose connect() function. Instead, the function returns a promise where you can handle it either for successful or error cases

    mongoose.connect(mogoURI)
      .then(() => console.log("Connected to Mongo Successfully"))
      .catch(error => handleError(error));
    

    Better way is to use JS await keyword:

    try {
      await mongoose.connect(mogoURI);
      console.log("Connected to Mongo Successfully");
    } catch (error) {
      handleError(error);
    }
    
    Login or Signup to reply.
  3. If you are using moongoose 5.x and onward, modifying your code in following way should fix it

      const mongoURI = "mongodb://localhost:27017/?directConnection=true";
    
    const connectToMongo = () => {
        mongoose.connect(mongoURI)
            .then(() => {
                console.log('Connected to Mongo Successfully');
            })
            .catch(err => {
                console.error('Failed to connect to Mongo: ' + err);
            });
    }
    

    Also Remember to call your connectToMongo() function somewhere in your code.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search