首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在NestJS Typescript中访问mongo .pre()钩子函数中的res、res

如何在NestJS Typescript中访问mongo .pre()钩子函数中的res、res
EN

Stack Overflow用户
提问于 2021-04-14 18:23:00
回答 1查看 69关注 0票数 0

大家好,我是TS和NestJS的新手,我正在努力访问预存钩子中的请求,res请检查我的文件和我得到的编译器错误的图像。有人能解释一下为什么我会收到这个错误吗?

此外,在Techniques > mongo > hook中的nestJs文档中,他们告诉我在Mongoose.forFeatureAsync()侧使用钩子,但我总是得到错误,我的用户模型没有注册,有人能提到最佳实践吗?我真的很难找到实现这一点的最佳实践谢谢您的宝贵时间

Image of error

代码语言:javascript
运行
复制
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();
});
EN

回答 1

Stack Overflow用户

发布于 2021-04-15 22:25:01

代码语言:javascript
运行
复制
///...
export const UserSchema = SchemaFactory.createForClass(User);

UserSchema.pre('save', function (this: UserDocument, next: any) {
  // ...
  next();
});
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67089884

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档