1

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, {}>

  • So I thought that Model is the type which I need to specify

This is how I tired to make this constructor

import { Model } from "mongoose";

class AuthController {
  constructor(userModel: Model) {}
}
  • But I am getting this error message: Generic type 'Model<T, QueryHelpers>' requires between 1 and 2 type arguments.t

  • Can I please get some help on this I was trying to avoid using the any datatype because I want to make sure that the constructor takes in those specified parameter types

1
  • 1
    I've never used a constructor with mongoose before. A Model type can be defined as Model<User> where you have to define User. interface User { name: string; } Commented Dec 7, 2020 at 17:53

1 Answer 1

2

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) {}
}
Sign up to request clarification or add additional context in comments.

6 Comments

Quick question so even if I were to pass Document as the datatype that would still hold as a valid mongoose model?
That is the datatype of the model. So it's what the model will return when queried, etc. Model<UserDocument> is saying "This is a mongoose model, that operates (find, update, etc) against UserDocuments"
Okay but when I write userModel: Document in my constructor the instance I try to use the .findOne() methods I get an error that the following method is not available
That is correct - Document is not the correct type. Model<Document> is. But that won't have any metadata on your actual documents, so Model<UserDocument> would be the way to go here.
Oh Yea I see what you mean thanks now it's working nicely thanks a lot...
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.