简体   繁体   中英

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?

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM