question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

How to represent and call methods, hooks on mongoose ES6 Classes

See original GitHub issue

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 have seen that in the latest nestjs mongoose release Cat Schema you have added the support for ES6 class, so that we can now write our mongoose schema definitions quite well in a class format. Thats awesome. But i had a quick question on the additional attributes that go along with the mongoose schema like methods, hooks. How do we represent them in our schema definitions and get that called in the services?

user.ts

import { Document } from 'mongoose';
import { SchemaFactory, Prop, Schema } from '@nestjs/mongoose';
import * as bcrypt from 'bcryptjs';

@Schema()
export class User extends Document {
    @Prop({ required: true })
    firstName: string;

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

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

    @Prop({ required: true, select: false })
    password: string;
    
    // For comparing passwords
    comparePassword(password: string) {
        return bcrypt.compareSync(password, this.password);
    }
}

export const UserSchema = SchemaFactory.createForClass(User);

Expected behavior

The expected behavior was that i could call the comparePassword function in my auth service like so:

auth.service.ts

   async validateUser(username: string, pass: string): Promise<any> {
        const user = await this.usersService.findOne(username);
        
        if (user && user.comparePassword(pass)) {
            const { password, ...result } = user;
            return result;
        }
        return null;
    }

But here i get an error from the typescript compiler that Property 'comparePassword' does not exist on type 'User'.ts

Any thoughts would be helpful.

Environment


Nest version: 7.0.0

 
For Tooling issues:
- Node version: v10.16.0
- Platform:  Mac

Others:

Issue Analytics

  • State:closed
  • Created 3 years ago
  • Reactions:12
  • Comments:19 (4 by maintainers)

github_iconTop GitHub Comments

15reactions
jcommented, Dec 9, 2020

@sandeepsuvit @beaucafe

What happens if you do this:

import { Document } from 'mongoose';
import { SchemaFactory, Prop, Schema } from '@nestjs/mongoose';
import * as bcrypt from 'bcryptjs';

@Schema()
export class User extends Document {
    @Prop({ required: true })
    firstName: string;

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

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

    @Prop({ required: true, select: false })
    password: string;
    
    // For comparing passwords
    comparePassword(password: string) {
        return bcrypt.compareSync(password, this.password);
    }
}

export const UserSchema = SchemaFactory.createForClass(User);

// This part here (see https://mongoosejs.com/docs/guide.html#es6-classes)
UserSchema.loadClass(User);
5reactions
beaucafecommented, Sep 23, 2020
import { Document } from 'mongoose';
import { SchemaFactory, Prop, Schema } from '@nestjs/mongoose';
import * as bcrypt from 'bcryptjs';

@Schema()
export class User extends Document {
    @Prop({ required: true })
    firstName: string;

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

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

    @Prop({ required: true, select: false })
    password: string;
    
    // Revise to Function
    comparePassword : Function
}

export const UserSchema = SchemaFactory.createForClass(User);

And create new methods under UserSchema.

UserSchema.methods.comparePassword = async function (password : string) {
  const isValid = await bcrypt.compare(password, this.password)
  return isValid
}

mongoos#es6-classes

Read more comments on GitHub >

github_iconTop Results From Across the Web

Mongoose v6.8.1: Middleware
Middleware (also called pre and post hooks) are functions which are passed control during execution of asynchronous functions. Middleware is specified on ...
Read more >
Mongoose model as an ES6 class with inheritance chain
I literally face this issue yesterday. Here is the code that I got working : class User extends mongoose.
Read more >
Node Auth Tutorial (JWT) #6 - Mongoose Hooks - YouTube
In this Node auth tutorial we'll take a look at how mongoose hooks can be used to fire code at different points when...
Read more >
Mongoose Pre-Save Hooks (144) - YouTube
DONATE TO THE SHOW !!!Donate any amount - https://bit.ly/2XmweLcMusic commonly used on this channel:http://birocratic.com ...
Read more >
Mongoose (validation + hooks = 🔥) | by Anand Deep
Mongoose uses an inbuilt validation function that validates the schema and also returns a custom message. ... phone: {type: String,required: [true, "Phone number ......
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found