SU7
SU7

Reputation: 1756

mongoose.connect(uri, ConnectOptions) does not recognize useNewUrlParser and other options

My GitHub repo: https://github.com/safiullah7/legan

Branch: redux

I'm following this tutorial: https://tomanagle.medium.com/build-a-rest-api-with-node-js-typescript-mongodb-b6c898d70d61 and I'm unable to connect to my mongodb. Here's my code file where I'm trying to connect with the mongodb:

import config from "config";
import log from "../logger";

function connect() {
  const dbUri = config.get("dbUri") as string;

  return mongoose
    .connect(dbUri, {
      useNewUrlParser: true,
      useUnifiedTopology: true,
    })
    .then(() => {
      log.info("Database connected");
    })
    .catch((error) => {
      log.error("db error", error);
      process.exit(1);
    });
}

export default connect;

Compiler gives the following error:

No overload matches this call.
  Overload 1 of 3, '(uri: string, callback: CallbackWithoutResult): void', gave the following error.
    Argument of type '{ useNewUrlParser: boolean; useUnifiedTopology: boolean; }' is not assignable to parameter of type 'CallbackWithoutResult'.
      Object literal may only specify known properties, and 'useNewUrlParser' does not exist in type 'CallbackWithoutResult'.
  Overload 2 of 3, '(uri: string, options?: ConnectOptions | undefined): Promise<typeof import("mongoose")>', gave the following error.
    Argument of type '{ useNewUrlParser: boolean; useUnifiedTopology: boolean; }' is not assignable to parameter of type 'ConnectOptions'.
      Object literal may only specify known properties, and 'useNewUrlParser' does not exist in type 'ConnectOptions'.

I'm new to typescript and node/mongoos. Would appreciate your help.

Upvotes: 17

Views: 33913

Answers (5)

const con = await mongoose.connect((process.env.MONGO_URI as string), {
  useNewUrlParser: true,
  useUnifiedTopology: true,
} as ConnectOptions)

The options usecreateindex, usefindandmodify are not supported.

Upvotes: 0

Alejandro Aburto
Alejandro Aburto

Reputation: 1402

UPDATE: Clarifying this answer as a reference for future readers.

This answer applies if you are using Mongoose v6+.

Other answers explain how to expand typescript to accept useNewUrlParser and other options, which would resolve the original question.

However, as per Mongoose documentation, if you are using Mongoose v6+, these options are NO longer required, as they have been included as defaults.

As per Mongoose migration guide to version 6:

useNewUrlParser, useUnifiedTopology, useFindAndModify, and useCreateIndex are no longer supported options. Mongoose 6 always behaves as if useNewUrlParser, useUnifiedTopology, and useCreateIndex are true, and useFindAndModify is false. Please remove these options from your code.

https://mongoosejs.com/docs/migrating_to_6.html#no-more-deprecation-warning-options

Therefore, it is no longer necessary to include these options. I would imagine this is why they are no longer included in ConnectOptions type.

If you are using an older version of Mongoose, refer to the other answers for how to expand ConnectOptions type to allow for these options.

Upvotes: 22

edumueller
edumueller

Reputation: 399

You can change your mongoose.connect function to:

mongoose.connect(dbUri, {
  useNewUrlParser: true,
  useUnifiedTopology: true,
} as ConnectOptions)

This is the simplest way

Upvotes: 39

Duy Huynh
Duy Huynh

Reputation: 186

So far, just waiting for new update from mongoose, in the meantime there is a workaround may help

import { ConnectionOptions, connect } from "mongoose"

type ConnectionOptionsExtend = {
  useNewUrlParser: boolean
  useUnifiedTopology: boolean
}

const options: ConnectionOptions & ConnectionOptionsExtend = {
  useNewUrlParser: true,
  useUnifiedTopology: true,
  authSource: "admin",
  useCreateIndex: true,
  useFindAndModify: false,
  user,
  pass
}

await connect(uri, options)

Upvotes: 1

Hoang
Hoang

Reputation: 411

The new version of mongoose (the latest version when I wrote this post is 6.0.2) has the following type definitions for the connect() function.

/** Opens Mongoose's default connection to MongoDB, see [connections docs](https://mongoosejs.com/docs/connections.html) */
export function connect(uri: string, options: ConnectOptions, callback: CallbackWithoutResult): void;
export function connect(uri: string, callback: CallbackWithoutResult): void;
export function connect(uri: string, options?: ConnectOptions): Promise<Mongoose>;

The options object you're passing to the connect() function

{
  useNewUrlParser: true,
  useUnifiedTopology: true,
}

is, therefore, should have a type of ConnectOptions.

Current definition of the ConnectOptions is as follows:

interface ConnectOptions extends mongodb.MongoClientOptions {
  /** Set to false to [disable buffering](http://mongoosejs.com/docs/faq.html#callback_never_executes) on all models associated with this connection. */
  bufferCommands?: boolean;
  /** The name of the database you want to use. If not provided, Mongoose uses the database name from connection string. */
  dbName?: string;
  /** username for authentication, equivalent to `options.auth.user`. Maintained for backwards compatibility. */
  user?: string;
  /** password for authentication, equivalent to `options.auth.password`. Maintained for backwards compatibility. */
  pass?: string;
  /** Set to false to disable automatic index creation for all models associated with this connection. */
  autoIndex?: boolean;
  /** Set to `true` to make Mongoose automatically call `createCollection()` on every model created on this connection. */
  autoCreate?: boolean;
}

Looking at the new definition of the connect and ConnectOptions, we can see that there is no definition of useNewUrlParser or useUnifiedTopology inside the ConnectOptions. That is the reason we got such an error. You can delete the options useNewUrlParser: true, and useUnifiedTopology: true, and your code should be able to connect to your MongoDB. If you want to pass in some options to the connect() function, then they should follow the new type definition of the ConnectOptions.

Upvotes: 24

Related Questions