Type error using useNewUrlParser with mongoose in TypeScript
Asked Answered
T

3

6

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.

Taryntaryne answered 25/5, 2019 at 16:0 Comment(1)
forgot to post an update: this must have been fixed in @types/mongoose, because I stopped seing this issue after upgrading it 1 or 2 weeks laterTaryntaryne
C
7

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();
})
Crittenden answered 7/2, 2022 at 3:21 Comment(1)
The question was valid on mongoose < 6. Also, @types/mongoose is no longer used as mongoose now includes typings nativelyTaryntaryne
E
0

You need to have dev dependency installed

npm install -D @types/mongoose --save
Earthshine answered 30/4, 2020 at 17:33 Comment(1)
I did say that it seemed to be an issue with @types/mongoose, meaning that it was obviously installed...Taryntaryne
S
0

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,
    ...
  },
  ...
}
Shien answered 17/4, 2021 at 22:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.