【问题标题】:Typescript Mongoose - methods / static functions not being called [ Kubernetes - Docker ]Typescript Mongoose - 方法/静态函数未被调用 [Kubernetes - Docker]
【发布时间】:2021-12-25 20:54:26
【问题描述】:

我在Kubernetes - Docker 中使用mongodb < TypeScript > 时遇到了一个问题。 我在 save 上添加了一个中间件,在 Model 上添加了一个静态函数。使用时不会调用它。它们都不起作用[中间件 - 静态函数]。

用户模型:

import { model, Schema, Model, Document } from "mongoose";
import { Password } from "../service/Password";
/**
 * @interface UserAttr
 * @description It helps the User Model in the moment of being createed
 */

interface UserAttrs {
  email: string;
  password: string;
}

/**
 * @interface UserModel
 * @description It helps the method of the user being detective on its own model
 */

interface UserModel extends Model<UserDocument> {
  build(attrs: UserAttrs): UserDocument;
}

/**
 * @interface UserDocument
 * @description It helps the document of the user to work more efficiently
 */

export interface UserDocument extends Document {
  email: string;
  password: string;
  createdAt: string;
  updatedAt: string;
}

const userSchema = new Schema(
  {
    email: {
      type: String,
      required: true,
    },
    password: {
      type: String,
      required: true,
    },
  },
  { timestamps: true }
);

const User = model<UserDocument, UserModel>("User", userSchema);

userSchema.statics.build = function (attrs: UserAttrs) {
  return new User(attrs);
};

userSchema.pre(
  "save",
  async function (this: UserDocument, next): Promise<void> {
    console.log("Saving . . . ");
    // const self = this as UserDocument;
    if (this.isModified("password")) {
      const hashedPassword = await Password.toHash(this.get("password"));
      this.set("password", hashedPassword);
    }
    next();
  }
);

export { User };

他们被使用的地方:

import { Router, Response, Request } from "express";
import { body, validationResult } from "express-validator";
import { BadRequestError } from "../../errors/BadRequestError";
import { RequestValidationError } from "../../errors/RequestValidationError";
import { User } from "../../models/user.model";

const router: Router = Router();

router.post(
  "/api/users/signup",
  [
    body("email")
      .not()
      .isEmpty()
      .withMessage("Email Field is empty. fill it please")
      .trim()
      .isEmail()
      .normalizeEmail()
      .withMessage("Email is not valid. "),
    body("password")
      .notEmpty()
      .withMessage("Password Field is empty. fill it please")
      .trim()
      .isLength({ min: 4, max: 12 })
      .withMessage("Password length is 4 - 12 characters"),
  ],
  async (req: Request, res: Response) => {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      throw new RequestValidationError(errors.array());
    }

    const { email, password } = req.body;

    const existingUser = await User.findOne({
      email,
    });

    if (existingUser) {
      throw new BadRequestError("Email in use");
    }

    const user = User.build({
      email,
      password,
    });

    await user.save();
    res.status(201).json(user);
  }
);

export { router as signUpRouter };

提示:我检查了模型本身 [ new User({...}) ] 并按预期工作。我不知道他们为什么不使用 middleware and static function

【问题讨论】:

    标签: typescript mongoose


    【解决方案1】:

    找了半天,自己找到了上述易出错模块的解决办法。

    解决方法:错误是上面写的代码的顺序。模型必须一直向下才能被识别。它根本不会对middlewares、Statics 和Methods 做出反应。确保在导出之前Model 一直向下当您设置一些以前的功能时。

    可能必须像以下步骤:

    import { model, Schema, Model, Document } from "mongoose";
    import { Password } from "../service/Password";
    /**
     * @interface UserAttr
     * @description It helps the User Model in the moment of being createed
     */
    
    interface UserAttrs {
      email: string;
      password: string;
    }
    
    /**
     * @interface UserModel
     * @description It helps the method of the user being detective on its own model
     */
    
    interface UserModel extends Model<UserDocument> {
      build(attrs: UserAttrs): UserDocument;
    }
    
    /**
     * @interface UserDocument
     * @description It helps the document of the user to work more efficiently
     */
    
    export interface UserDocument extends Document {
      email: string;
      password: string;
      createdAt: string;
      updatedAt: string;
    }
    
    const userSchema = new Schema(
      {
        email: {
          type: String,
          required: true,
        },
        password: {
          type: String,
          required: true,
        },
      },
      { timestamps: true }
    );
    
    userSchema.statics.build = function (attrs: UserAttrs) {
      return new User(attrs);
    };
    
    userSchema.pre(
      "save",
      async function (this: UserDocument, next): Promise<void> {
        console.log("Saving . . . ");
        // const self = this as UserDocument;
        if (this.isModified("password")) {
          const hashedPassword = await Password.toHash(this.get("password"));
          this.set("password", hashedPassword);
        }
        next();
      }
    );
    
    const User = model<UserDocument, UserModel>("User", userSchema);
    
    export default User;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-09
      • 2020-06-13
      • 1970-01-01
      • 2014-07-03
      • 2014-10-28
      • 1970-01-01
      相关资源
      最近更新 更多