问题描述
我正在使用 "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,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 的中间件。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)