【发布时间】: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