plus-
plus-

Reputation: 46543

Mongoose: middleware for all save and update methods

I've been writing a CRUD app using mongoose following API:

I'd like to have a middleware fire for both those methods. I've tried pre('save', ...) pre('validate', ...) but that they only fire for the create route.

Is there something else which works for both or do I need to refactor the update route to make use of the save() API?

Upvotes: 2

Views: 1221

Answers (2)

arg20
arg20

Reputation: 4991

What you could do is wrap your Model in some service that extends events.EventEmitter, then use that service to perform updates on your models, have it emit an event when this happens and then all functions interested in responding to those updates can just register to it.

Besides this, there is no other way so far to have middleware called when the database calls execute.

As an example you could have something like:

function FooService() {
    var self = this
    var Foo = require('./path/to/foo/module')    

    this.edit = function(id, changes) {
         Foo.findByIdAndUpdate(id, changes, function(err) {
              if (!err) {
                  self.emit('FooUpdated', id)
              }
         })
    }
}

util.inherits(FooService, events.EventEmitter)
module.exports = new FooService()

This way if anyone is interested in knowing when foo is updated, they can just require the service and do: FooService.on('FooUpdated', function(id){...})

This works nicely if you need to update references or denormalize, you can be sure that using that service no matter what you do, you always have an event triggered and Foo doesn't need to be aware of how many other Services need to be notified.

Upvotes: 0

JohnnyHK
JohnnyHK

Reputation: 312005

The 'save' middleware only fires on save calls, not on any of the update calls. There's no middleware that fires for the updates as those are sent right to the driver so that they're atomic.

Upvotes: 6

Related Questions