我正在使用"mongoose-extend-schema": "^1.0.0"
mongoose 将基本模式添加到所有其他模式。
这是我的代码:
import mongoose from "mongoose";
interface IBaseSchema extends mongoose.Document {
createdBy: string;
updatedBy: string;
isDeleted: boolean;
}
const BaseSchema = new mongoose.Schema({
createdBy: {
type: String,
default: "some User"
},
updatedBy: {
type: String,
default: "some user"
},
isDeleted: {
type: Boolean,
default: false
}
});
BaseSchema.pre<IBaseSchema>("save", async function (next) {
this.createdBy = "from the middleware";
this.updatedBy = "from the middleware fun";
next();
});
export default BaseSchema;
然后我在用户模型中使用它
import { IUser } from "../interfaces/IUser";
import mongoose from "mongoose";
import extendSchema from "mongoose-extend-schema";
import { StatusTypesEnum, UserTypesEnum } from "./enums";
import BaseSchema from "./baseModel";
const User = extendSchema(BaseSchema,
{
firstName: {
type: String,
required: true
},
lastName: {
type: String,
required: true
},
avatar: {
type: String,
},
status: {
type: String,
enum: StatusTypesEnum
},
type: {
type: String,
enum: UserTypesEnum
},
businessOwner: {
storeId: String
},
},
{ timestamps: true }
);
export default mongoose.model<IUser & mongoose.Document>("user", User);
我期待在保存用户时,预“保存”中间件也将执行和更新 createdBy 和 updatedBy 的字段,但它没有工作。
但是如果我在用户模型中添加中间件,比如
User.pre<any>("save", async function (next) {
this.createdBy = "from the middleware";
this.updatedBy = "from the middleware fun";
next();
});
它显示了变化。
如何直接从 baseModel 文件运行影响 baseModel 的中间件。