Home > Back-end >  Nestjs mongoose access different schema on pre-save
Nestjs mongoose access different schema on pre-save

Time:10-19

How can I access another table within the pre-save schema event?

mySchema.pre('save',()=>{
 // FindAndUpdate another schema
})

CodePudding user response:

You have to use factory in order to achieve this. It is also mentioned in the documentation (https://docs.nestjs.com/techniques/mongodb):

You can use the following code:

@Module({
  imports: [
    MongooseModule.forFeatureAsync([
      {
        name: MySchema.name,
        useFactory: (otherSchemaModel: Model<OtherSchemaDocument>) => {
          const mySchema = MySchema;
          mySchema.pre('save', function () {
            // use otherSchemaModel here
          });
          return mySchema;
        },
        inject: [getModelToken("OtherSchemaToken"))],
      },
    ]),
  ],
})

Note: You should probably define the factory method somewhere else and import it in your module.

  • Related