Ways to retrieve req and res within a function in the .pre() hook of MongoDB in NestJS with Typescript

Hello everyone! I am a beginner in TS and NestJS, and I'm having trouble accessing req and res inside a pre-save hook. Can someone please take a look at my file and the image of the compiler error that I'm encountering? Could you explain why this error is happening?

Also, in the NestJs documentation under Techniques > mongo > hook, they suggest using hooks inside Mongoose.forFeatureAsync(), but I keep getting an error saying that my user model wasn't registered. Can anyone recommend the best practice for achieving this? I'm really struggling to figure out the best approach. Thank you for your time.

Here is the image of the error.

user.model.ts -

import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { Document } from 'mongoose';
import * as mongoose from 'mongoose';
import { Req , Res } from '@nestjs/common';

export type UserDocument = User & Document;

@Schema()
export class User {
  constructor() {}
  @Prop({
    required: [true, 'Please enter first name'],
    trim: true,
  })
  firstName: string;

  @Prop({
    required: [true, 'Please enter last name'],
    trim: true,
  })
  lastName: string;

  @Prop({
    type: mongoose.Schema.Types.ObjectId,
    ref: 'User',
  })
  referer: mongoose.Types.ObjectId;

  @Prop({
    type: [
      {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'User',
      },
    ],
  })
  referees: mongoose.Types.ObjectId[];

  @Prop()
  referralCode: string;

  @Prop({
    default: 0,
  })
  transactions: number;

  @Prop({
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Account',
  })
  account: mongoose.Types.ObjectId;
}

export const UserSchema = SchemaFactory.createForClass(User);

UserSchema.pre('save', function ( req , res , next) {
  let referralCode;
  const random = Math.floor(Math.random() * 1000);
  const number = random.toLocaleString('en-US', {
    minimumIntegerDigits: 3,
    useGrouping: false,
  });
  const finalNumber = number.toString();
  const name = this.get('firstName');
  if (name.length < 5) {
    const repeat = 5 - name.length;
    const str = 'X';
    const repeatedString = str.repeat(repeat);
    referralCode = name.concat(repeatedString).concat(finalNumber);
  } else {
    referralCode = name.substr(0, 5).concat(finalNumber);
  }
  this.set('referralCode', referralCode);
  console.log(this);
  next();
});

Answer №1

///...
const NewUserSchema = SchemaFactory.createForClass(User);

NewUserSchema.pre('save', function (this: UserDocument, next: any) {
  // ...
  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

Determine whether one class is a parent class of another class

I'm working with an array of classes (not objects) and I need to add new classes to the array only if a subclass is not already present. However, the current code is unable to achieve this since these are not initialized objects. import {A} from &apo ...

Encountered a bun runtime error stating "Possibly require an `extends React.JSX.IntrinsicAttributes` constraint for this type parameter."

I have a good understanding of ReactJS, but this topic seems to be more advanced. I am working with generics in TypeScript and have the following code: export const withPopover = <T,>(WrappedComponent: React.ComponentType<T>) => { const ...

The custom component in ngx-formly remains unchanged after updating the model

I am utilizing custom component fields in my project. Initially, everything works smoothly until I attempt to replace the model with a different one. Unfortunately, the component for each field does not get updated with the new value. No events seem to ...

What is the best way to fetch data before a component is rendered on the screen?

I am facing an issue with fetching data from a local server in Node. When I try to render the component, the array 'users' from the state appears to be empty, resulting in no users being displayed on the screen as intended. What's strange is ...

MongoDB (Potential number of _id variations)

In the realm of mongoose, there exists a model named Post (defined as var Post = new Schema({...});). Each time a new instance of the Post model is created (var post = new Post({...}); post.save(function (error) {...});), it is assigned a special item kn ...

When working with Typescript, an error is thrown if property "p" does not exist on one of the classes that are OR

In my component class, I have a property called renderContent which can be of either LessonPageType or TaskPageType based on the input value. Below is the code snippet from my component: import {ChangeDetectionStrategy, Component, HostListener, Input, OnI ...

Tips for correctly initializing documents in a mongoose collection

Can you provide feedback on my proposed design? I have a blog post model that includes a "category" field. My goal is to allow users to enter a category using typeahead, and if the desired category is not in the list, they should be able to create it. How ...

What is the mechanism behind the widening of object literal types in Typescript inference?

I've been reading up on how typescript broadens inferred types but I'm still not entirely clear about what's happening here: type Def = { 'T': { status: 5, data: {r: 'm'}}, } function route<S extends keyof Def> ...

Execute the function right away and then at regular intervals of X seconds

Need help with Angular 7 function call timing checkData(): Observable<string> { return this.http.get('') .pipe( map(res => { let result; result = { packageNumbe ...

Deactivate the selection option in Syncfusion NumericTextbox

I have integrated an Angular NumericTextbox component from Syncfusion into my application. A problem we encountered is that when the input is clicked, it automatically gets selected. Is there a way to disable this behavior? Problem: https://gyazo.com/a72b ...

Having trouble uploading images with Expo ImagePicker in ReactNative?

After selecting an image from the FileManager and receiving a result, I noticed that the data passed to Node.js is in an array of arrays format. The image data is being sent along with other data in FormData. While I can successfully send the data to Nod ...

Aurelia - Struggling to integrate CssAnimator with a basic message div

Currently, I am utilizing Typescript and referencing an informative blog post by Mikhail Shilkov. Even though I am implementing Typescript, the blog post revolves around Javascript. This has led me to ponder whether this difference is the root cause of th ...

Storing data using mongoose does not alter the existing information

I encountered an issue with my code while trying to update an object fetched from a MongoDB. The object contains a map with an array, and I am pushing new values to that array within the map successfully. However, even though the object itself reflects the ...

Modify every audio mixer for Windows

Currently working on developing software for Windows using typescript. Looking to modify the audio being played on Windows by utilizing the mixer for individual applications similar to the built-in Windows audio mixer. Came across a plugin called win-audi ...

The Power of Angular 2's Reactive Form Validation

I am currently developing a custom validator for a group of inputs within my dynamic form. this.transitionForm = this.fb.group({ effectiveStartDate: [this.utils.dateToISO(startDate), Validators.compose([Validators.required, this.validateDates])], effe ...

What is the best way to delete a nested document within an array in MongoDB by referencing its _id?

I am trying to remove a nested object from an array of objects called createdEvents if the createdEventId matches the id I pass to it. This is the JavaScript query I am using: db.collection("users").updateOne({ _id: userId }, { $pull: { createdEv ...

Delete the file containing Mongoose references

I'm facing an issue with deleting questions when a survey is deleted in the Survey model. Even after deleting the survey, the question remains intact in the database. Survey Schema: let surveyModel = mongoose.Schema( { Title: String, T ...

Determining the Optimal Mongo Shard Size for Backup Efficiency

Is there an optimal shard size for efficient backups? A member of the operations team mentioned that they currently have 3 shards, each with 350GB of data, and it takes 12.5 hours to complete a backup. If only a maximum data loss of 5 minutes is permitte ...

Excluding a common attribute from a combined type of objects can lead to issues when accessing non-common attributes (TypeScript)

In the process of developing a wrapper function, I am passing a refs property into a send function. The Event type used to construct my state machine is defined as an intersection between a base interface { refs: NodeRefs } and a union of possible event ob ...

The functionality of CSS transitions may be affected when dynamically adding a class

Creating a custom CSS for my main div: .main { height: 0%; position: absolute; width: 100%; z-index: 100; background: whitesmoke; bottom: 0; border-radius: 15px; padding: 20px; color: gray; left: 0; right: 0; transition: height 1s e ...