0

Mongoose Schema Class Mongoose collection user schema

const UserSchema = new Schema({
  firstName: {
    type: String,
    required: true,
  },
  lastName: {
    type: String,
    required: true,
  },
  gender: {
    type: String,
    enum: Object.keys(GenderType),
    required: true,
  },
});

UserSchema.methods = {

  fullName(): string {
    return `${this.firstName} ${this.lastName}`;
  },

};

UserSchema.statics = {

  someAction(): string {
    return '123';
  },

};

export default UserSchema;

Document Interface Class

Mongoose collection interface class

export interface IUser extends Document {

  _id: Types.ObjectId;
  firstName: string;
  lastName: string;
  gender: string;

  fullName: () => string;
}

How to define static mongoose methods in document interface while using @nestjs/mongoose?

Frozenex
  • 450
  • 6
  • 13

1 Answers1

4

In addition to IUser, you might want to have an extra interface IUserModel and extends it from Model<T>. Sample snippet might look as follow:

export interface IUserModel extends Model<IUser> {
     // Model is imported from mongoose
     // you can put your statics methods here
     someAction: () => string;
}

Then in wherever you're injecting the Model using @InjectModel(), you can type your injection of type IUserModel.

constructor(@InjectModel('UserModel') private readonly userModel: IUserModel) {}

Now your this.userModel will have access to someAction() method.

Happy coding!

Chau Tran
  • 4,668
  • 1
  • 21
  • 39