1

i am using "mongoose-extend-schema": "^1.0.0" with mongoose to add a base schema to all other schemas.

here is my code:

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;

and then i used it in user model

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);

i was expecting that on saving a user the pre "save" middleware will also execute and update the fields of createdBy and updatedBy, but it did not work.

but if i added the middleware in user model like

User.pre<any>("save", async function (next) {
  this.createdBy = "from the middleware";
  this.updatedBy = "from the middleware fun";
  next();
});

and it showed the changes.

how can i run the middleware affecting baseModel directly from baseModel file.

Shubham Shaw
  • 841
  • 1
  • 11
  • 24

0 Answers0