'Type error using useNewUrlParser with mongoose in TypeScript

I'm doing the following:

// Connect to MongoDB
mongoose.connect(MONGODB_URI, { useNewUrlParser: true, useCreateIndex: true }).then(
  () => { /** ready to use. The `mongoose.connect()` promise resolves to undefined. */ },
).catch((err: Error) => {
  console.log('MongoDB connection error. Please make sure MongoDB is running. ' + err)
  process.exit();
})

and I'm getting the following error from WebStorm TypeScript service (running TSLint manually works fine):

TS2345: Argument of type '{ useNewUrlParser: boolean; useCreateIndex: boolean; }' is not assignable to parameter of type '(err: MongoError) => void'. Object literal may only specify known properties, and 'useNewUrlParser' does not exist in type '(err: MongoError) => void'.

This seems to be an issue with @types/mongoose, but I've looked everywhere and I can't find where it's coming from.

Here is a workaround which does not really explain the issue:

    mongoose.set('useNewUrlParser', true)
    mongoose.set('useCreateIndex', true)
    mongoose.connect(MONGODB_URI).then(...

Edit: mongoose 6 no longer need these options.



Solution 1:[1]

These options are no longer necessary; hence why they aren't even in the type definitions. See the docs here: https://mongoosejs.com/docs/migrating_to_6.html#no-more-deprecation-warning-options

// Connect to MongoDB
mongoose.connect(MONGODB_URI).then(
  () => { /** ready to use. The `mongoose.connect()` promise resolves to undefined. */ },
).catch((err: Error) => {
  console.log('MongoDB connection error. Please make sure MongoDB is running. ' + err)
  process.exit();
})

Solution 2:[2]

You need to have dev dependency installed

npm install -D @types/mongoose --save

Solution 3:[3]

Unfortunately Mongoose library can throw errors even with type definitions are installed:

yarn add @types/mongoose  or  npm i --save-dev @types/mongoose

One of the remedy is to add the option skipLibCheck: true in tsconfig.json:

{
  "compilerOptions": {
    ...
    "skipLibCheck": true,
    ...
  },
  ...
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 oriont
Solution 2 Hitesh Gautam
Solution 3 Roman