Simple post-create hook plugin for mongoose

Let's add a homemade mongoose hook that will trigger on document creation.

Currently, it is quite easy to add post save hooks on a document using

MyModel.post('save', function (doc){…})

But mongoose currently lacks an important feature: adding post "create" hooks.This can easily be implemented as follows.

1. Usage:

We are going to write a simple module that will allow to add post save hooks easily:

2. The Code:

First, create a postCreate.js file:

And of course, how good would it be without no specs ?

This piece of code is quite self-explicit: we add a _wasNew key to the object, which does not persist in the db. The async library is then used to run all the added listeners in parallel when the _wasNew key is found. The _wasNew is then removed so the callbacks are not triggered again.

Well, that wasn't that hard.

Happy coding !