Nest: Mongoose static/methods in Schema

Created on 18 Apr 2018  路  3Comments  路  Source: nestjs/nest

I'm submitting a...


[ ] Regression 
[ ] Bug report
[ ] Feature request
[x] Documentation issue or request
[ ] Support request => Please do not submit support request here, instead post your question on Stack Overflow.

Current behavior

I don't know how to make TS working with .static or .methods on mongoose Schema. I want to do something like this:

UserSchema.methods.comparePassword = function(pwd, callback) {
  // this.password typing is does not available in here
}

Is there possibility to make it work?

Most helpful comment

If you are willing to make a change in schema definitions, you could check out typgoose a library that makes mongoose more typescript friendly. I made a typegoose nestjs package that makes typegoose easy to use in a nestjs project.

For example,

export class User extends Typegoose {
  @prop({required: true, unique: true})
  username: string;

  @prop({required: true})
  password: string;

  @prop({required: true})
  email: string;

  @prop({required: true})
  firstName: string;

  @prop({required: true})
  lastName: string;

  // this.password typing works for the following instanceMethod
  @instanceMethod
  async matchPassword(this: InstanceType<User>, password: string) {
    return await bcrypt.compare(password, this.password);
  }
}

All 3 comments

If you are willing to make a change in schema definitions, you could check out typgoose a library that makes mongoose more typescript friendly. I made a typegoose nestjs package that makes typegoose easy to use in a nestjs project.

For example,

export class User extends Typegoose {
  @prop({required: true, unique: true})
  username: string;

  @prop({required: true})
  password: string;

  @prop({required: true})
  email: string;

  @prop({required: true})
  firstName: string;

  @prop({required: true})
  lastName: string;

  // this.password typing works for the following instanceMethod
  @instanceMethod
  async matchPassword(this: InstanceType<User>, password: string) {
    return await bcrypt.compare(password, this.password);
  }
}

Wow, I didn't know about this package, I really wanted to use Typegoose earlier, now its possible. Thank you!

This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

FranciZ picture FranciZ  路  3Comments

menme95 picture menme95  路  3Comments

anyx picture anyx  路  3Comments

thohoh picture thohoh  路  3Comments

breitsmiley picture breitsmiley  路  3Comments