Secure Your Passwords with Encryption in NestJS using @nestjs/mongoose before saving them

Seeking to encrypt passwords before saving using @nestjs/mongoose. Came across examples written in pseudocode like this:

UsersSchema.pre('save', (next: any) => {
  if (!this.isModified('password')) return next();
  this.password = encrypt(this.password, 10);
  next();
});

However, there doesn't seem to be a specific type assigned to 'this', so I logged it to see more information, and it turns out to be a different object altogether.

// user.entity.ts
const UsersSchema = SchemaFactory.createForClass(Users);

UsersSchema.pre('save', () => {
  console.log(this);
});

export { UsersSchema };

Here's the log result:

 {
   Users: [class Users],
   UsersSchema: Schema {
     obj: {
       username: [Object],
       name: [Object],
       email: [Object],
       password: [Object]
     },
     paths: {
       username: [SchemaString],
       name: [SchemaString],
       email: [SchemaString],
       password: [SchemaString],
       _id: [ObjectId],
       __v: [SchemaNumber]
     },
     aliases: {},
     subpaths: {},
     ...and more

I'm unsure about how this behavior works as it wasn't found in the documentation. Could use some guidance on whether I'm approaching this correctly?

Answer №1

This method is my preferred choice because it directly connects the code to the specific object.

import { hashSync } from 'bcrypt';

@Schema({ timestamps: true })
export class User {
  @Prop({
    set: (input: string) => hashSync(input, 10),
  })
  password: string;
}

Answer №2

In the @nestjs/mongoose package, the hook function pre and post(['save', 'findOneAndUpdate']) is commonly utilized within the useFactory function.

However, in order to access your documents, you need to pass docs and next as depicted below

@Module({
  imports: [
    MongooseModule.forFeatureAsync([
      {
        name: Dog.name,
        imports: [ConfigModule],
        useFactory: (configService: ConfigService) => {
          const schema = AccountSchema;
          schema.pre('save', function(docs, next: NextFunction) {
            if(docs!.isActive){
              //send New Notification
            }
          });
          return schema;
        },
        inject: [ConfigService],
      },
    ]),
  ],
})
export class AppComponent {}

CatsSchema.pre('save', function (documents, next: NextFunction)  {

Answer №3

Consider switching from using an arrow function to a regular function in your code, it might help resolve the issue at hand!

UsersSchema.pre('save', function (next: any)  {
  if (!this.isModified('password')) return next();
  this.password = encrypt(this.password, 10);
  next();
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Execute a Typescript function where parameters are passed to another function

In my coding project, I came across a situation where I needed to write a method in Typescript. This method should allow me to run some checks and, if those conditions are met, return the result of another method. What I want is to pass a method along with ...

Arranging an array of objects in Javascript based on the first attribute, and in cases of equality, sorting with another attribute

I have an array structured like this: let myarr = [{id:1 , name: "mark" , birthday: "1990-08-18"}, {id:2 , name: "fred" , birthday: "1990-08-17"}, {id:3 , name: "franck" , birthday: "1990-08-16"}, ...

Don't forget to include the line 'import "reflect-metadata"' at the beginning of your entry point for Jest tests

As I work on developing an application using dependency injection with tsyringe, I came across a case where a service receives the repository as a dependency. Here is an example: import { injectable, inject } from 'tsyringe' import IAuthorsRepos ...

Delete a particular item from a JSON object in real-time using TypeScript/JavaScript

Upon examining the JSON data provided, it contains a node called careerLevels which includes inner child elements. input = { "careerLevelGroups": [ { "201801": 58, "201802": 74, ...

Encountering an issue with creating an App Runner on AWS CDK

Attempting to deploy my application using App Runner within AWS via CDK. Utilizing the reference from https://docs.aws.amazon.com/cdk/api/latest/docs/@aws-cdk_aws-apprunner.Service.html. Upon deployment, encountering the following error: create_failed: R ...

Typescript: The type 'T' fails to meet the requirement of being an 'object'

Ever since I installed a package along with its @types package, I've been encountering an issue with the following code: https://i.stack.imgur.com/rrRhW.png This is the error message that I'm receiving: https://i.stack.imgur.com/BfNmP.png The ...

What is causing the geolocation heading to remain "null" on Android devices when using Chrome?

Recently, I developed a compact geolocation watch using the following code snippet: navigator.geolocation.watchPosition( this.updateLocation.bind(this), this.errorLocation.bind(this), {enableHighAccuracy: true} ); The function updateLocation ...

Error: The script cannot be compiled with the '--isolatedModules' flag as it is recognized as a global script file

Currently, I am working on building my NextJS app and incorporating Cypress for testing along with Typescript. During this process, I encountered the following error: Type error: 'home.cy.ts' cannot be compiled under '--isolatedModules' ...

Angular - The filter method cannot be used on Observables

I have a database with users who need to complete unique homework sessions. Each homework session has its own identifier, name, date, and other details. After fetching all the user's homework from the database, it is stored in a private variable call ...

Utilizing symbols as a keyof type: A simple guide

Let's consider the following: type Bar = keyof Collection<string> In this scenario, Bar denotes the type of keys present in the Collection object, such as insert or remove: const x: Bar = 'insert'; ✅ But wait, the Collection also c ...

What exactly is the data type of setInterval in TypeScript?

If I want to define the type of a variable that will be used with setInterval in the following code snippet: this.autoSaveInterval = setInterval(function(){ if(this.car.id){ this.save(); } else{ this.create(); } ...

Is there an option for keyPrefix in i18next?

For my current project, I am utilizing both i18next and react-i18next. One useful feature of using the useTranslation hook from react-i18next is the "keyPrefix" option, which helps in reducing code duplication. However, there are instances where I need to ...

Are all components in Next.js considered client components by default?

I have created a Next.js app using the app folder and integrated the Next Auth library. To ensure that each page has access to the session, I decided to wrap the entire application in a SessionProvider. However, this led to the necessity of adding the &apo ...

Having trouble getting the npm package with @emotion/react and vite to function properly

Encountering an issue with the npm package dependencies after publishing, specifically with @emotion/react. This problem arose while using vite for packaging. Upon installing the package in another project, the css property appears as css="[object Ob ...

What kind of output should a Server Side Component generate?

Recently, I decided to incorporate the NextPage type from Next.js into my component writing routine after hearing it's a beneficial practice. However, I discovered that it only functions properly with client-side components. When attempting to utilize ...

Error encountered during Angular unit testing: Unable to read the 'id' property of a null value. (Jasmine, Karma)

I am currently working on writing unit tests for a specific component in my Angular application. The component uses a currentUser variable both in the component logic and the HTML template. I have hardcoded this variable by mocking it in every test using c ...

How to Change the Checked State of a Checkbox in React Material UI

I am faced with a situation where I have multiple checkboxes that are used to toggle table columns on and off. The code snippet demonstrates how it looks: const [fields, setFields] = useState<Set<string>>(new Set(["name"])); const ...

Sending a POST request to an API with Angular and passing an object as the payload

I'm currently working on adding a feature to my app where I can take the products from an order and send them to the cart, essentially replicating the entire order. While I have successfully retrieved the order, I am facing difficulty in sending it b ...

Using React and TypeScript together can lead to issues when trying to use union keys as an index

I've implemented a hook using useState and the delete method to effectively manage my form values. const [values, setValues] = useState<tAllValues>({}); The values stored include: { name: 'Andrew', age: 34, avatar: [{ name: ...

Best practice for validating a form using React: Why the state doesn't update immediately with useState and onSubmit

I'm currently working on implementing a custom form validation for my React project using Typescript. However, I've encountered an issue with the useState hook not updating the state containing errors immediately upon form submission. Let me illu ...