微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在模型中添加预中间件以在 mongoose 中扩展

如何解决在模型中添加预中间件以在 mongoose 中扩展

我正在使用 "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 举报,一经查实,本站将立刻删除。