#Mongodb update middleware not working inside Injectable

6 messages · Page 1 of 1 (latest)

acoustic dove
#

Hello,

I want to create a middleware to detect when a document is updated in my collection.

The goal is to reset the cache of the route when a document is updated.

So, I wanted to call a post-schema listener like this: when a schema is updated, it calls my function.

I have implemented something like this:

// cats.schema.ts

Cats.post(
  [
    'save',
    'deleteMany',
    'findOneAndDelete',
    'findOneAndReplace',
    'findOneAndUpdate',
    'replaceOne',
    'updateMany',
    'updateOne',
    'deleteOne',
  ],
  function (doc) {
    console.log(doc);
  },
);

Right below SchemaFactory.createForClass.

But now, I need to place it in a NestJs @unborn owlable class. This way, I can have access to the cacheManager (or @nestjs/event-emitter; this is how I want to call my reset cache function).

However, when I put the same code in onModuleInit, it's not working. The console.log(doc) is not called.

// cats.repository.ts

  onModuleInit() {
    console.log('Here');
Cats.post(
  [
    'save',
    'deleteMany',
    'findOneAndDelete',
    'findOneAndReplace',
    'findOneAndUpdate',
    'replaceOne',
    'updateMany',
    'updateOne',
    'deleteOne',
  ],
  function (doc) {
    console.log(doc);
  },
);
  }

Do you have any idea of how I can achieve this? Or perhaps if I can directly call an event outside an @unborn owlable class?

Thanks

acoustic dove
#

Did I forget any details? I need to accomplish something similar, but I'm unsure where is the issue.

eager iris
#

@acoustic dove - You are speaking of a Mongoose middleware, right? You'd normally "define" a middleware as part of the schema. And, that schema definition, with the addition of the middleware, can be defined in a module in the forFeature method creating your model, right?

Is that the right take of what you are wanting to do?

acoustic dove
#

I conducted some research but realized I was looking in the wrong place. I was referring to the Mongoose documentation here: https://mongoosejs.com/docs/middleware.html, but I needed to check the NestJS documentation with Mongoose instead:
https://docs.nestjs.com/techniques/mongodb#hooks-middleware

Now, I've attempted to inject my EventEmitter2, and it's working!

MongooseModule.forFeatureAsync([
  {
    name: CatsSchema.name,
    inject: [EventEmitter2],
    useFactory: (eventEmitter: EventEmitter2) => {
      const schema = CatsSchema;
      schema.post('save', function () {
        console.log('Here');
        eventEmitter.emit('cats.collection-updated');
      });
      return schema;
    },
  },
])
eager iris
#

So, is your problem solved?

acoustic dove
#

Yes thanks !