Syffys
Syffys

Reputation: 610

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.

Upvotes: 6

Views: 9852

Answers (3)

oriont
oriont

Reputation: 752

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();
})

Upvotes: 7

Roman
Roman

Reputation: 21767

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,
    ...
  },
  ...
}

Upvotes: 0

Hitesh Gautam
Hitesh Gautam

Reputation: 11

You need to have dev dependency installed

npm install -D @types/mongoose --save

Upvotes: 0

Related Questions