3

i got this error in my terminal when i run my index.js file as a 'npx nodemon .\index.js'

this is my 'index.js':

const connectToMongo = require('./database');
connectToMongo();

this is my dabase.js:

const mongoose = require('mongoose')
const mongoURI = 'mongodb://localhost:27017/'

const connectToMongo = ()=>{
    mongoose.connect(mongoURI,()=>{
        console.log('connected to mongo')
    })
}

module.exports = connectToMongo;
   

this is my terminal error:

  throw new MongooseError('Mongoose.prototype.connect() no longer accepts a callback');
      ^

MongooseError: Mongoose.prototype.connect() no longer accepts a callback at Mongoose.connect (D:\React\inotebook\backend\node_modules\mongoose\lib\index.js:400:11) at connectToMongo (D:\React\inotebook\backend\database.js:5:14) at Object. (D:\React\inotebook\backend\index.js:2:1) at Module._compile (node:internal/modules/cjs/loader:1254:14) at Module._extensions..js (node:internal/modules/cjs/loader:1308:10) at Module.load (node:internal/modules/cjs/loader:1117:32) at Module._load (node:internal/modules/cjs/loader:958:12) at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12) at node:internal/main/run_main_module:23:47 Node.js v18.14.1

i have not so much idea about nodemon so help me

mbojko
  • 13,503
  • 1
  • 16
  • 26
Chirag Kanani
  • 31
  • 1
  • 3

1 Answers1

2
const mongoose = require('mongoose');
const mongoURI = "mongodb://localhost:27017"

const connectToMongo = async () => {
try {
    mongoose.set('strictQuery', false)
    mongoose.connect(mongoURI) 
    console.log('Mongo connected')
}
catch(error) {
    console.log(error)
    process.exit()
}
}
module.exports = connectToMongo;

this worked for me

ti.tanicc
  • 21
  • 1
  • You might not need to add the `process.exit()` line there, as that action (i.e. stopping the entire application) might not necessarily be the action a user might want to take should the connection fail. – Deolu A Apr 15 '23 at 20:24