Ntshembo Hlongwane
Ntshembo Hlongwane

Reputation: 1051

What is the type for Mongoose collection model when using TypeScript

Hello guys this is my first time using TypeScript so I want to build an Auth controller class which takes in mongoose model in constructor and many others but the problem that I am facing I seem to not find the datatype / type for a mongoose model

When I hovered on top of the mongoose model I see the following: const model: Model<Document, {}>

This is how I tired to make this constructor

import { Model } from "mongoose";

class AuthController {
  constructor(userModel: Model) {}
}

Upvotes: 1

Views: 437

Answers (1)

AdamExchange
AdamExchange

Reputation: 1301

You should be able to solve this using

Model<UserDocument>

Where UserDocument is a type that extends mongooses Document type, like:

import { Document } from 'mongoose';
UserDocument = Document & { email: string } // Whatever user fields you have

Another way to solve this would be to have your User Model exported from its file:

export default mongoose.model<UserDocument>('User', UserSchema)

Then to use that exported model in your constructor

import UserModel from "./user-model";

class AuthController {
  constructor(userModel: UserModel) {}
}

Upvotes: 2

Related Questions