Alex Ironside
Alex Ironside

Reputation: 5039

Typing mongoose.connect

I'm trying to find a type for this:

export const connectToDatabase = ()/* here */ => mongoose.connect(uri, {
  useNewUrlParser: true,
  useUnifiedTopology: true,
});

So far my code editor suggested this:

export const connectToDatabase = ():
    Promise<typeof mongoose> => mongoose.connect(uri, {
  useNewUrlParser: true,
  useUnifiedTopology: true,
});

Which is silly. I don't want the type to be Promise<typeof mongoose> and it can't possibly be the desired solution. So what's the right type here? All I could find was ConnectionUseDbOptions and ConnectionOptions which doesn't work. So what's the correct type here?

Upvotes: 0

Views: 71

Answers (1)

Anatoly
Anatoly

Reputation: 22748

According to index.d.ts in @types/mongoose:

type Mongoose = typeof mongoose;
...
export function connect(uris: string, options: ConnectionOptions, callback: (err: mongodb.MongoError) => void): Promise<Mongoose>;
export function connect(uris: string, callback: (err: mongodb.MongoError) => void): Promise<Mongoose>;
export function connect(uris: string, options?: ConnectionOptions): Promise<Mongoose>;

So definitely the return type is Promise<Mongoose> or Promise<type of mongoose>

Upvotes: 1

Related Questions