Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose - how to tap schema middleware into the 'init' event?

It is suggested in the Mongoose docs that I should be able to control the flow using middleware that plugs in to the "init" hook.

However, I have so far had success only with "save" and "validate".

When I do something like this, neither of these middleware ever get called:

MySchema.post( "init", function (next) { console.log("post init") });
MySchema.pre( "init", function (next) { console.log("pre init") });

Am I missing something?

like image 529
ragulka Avatar asked Aug 31 '12 19:08

ragulka


People also ask

In which operations does Mongoose support middleware?

Mongoose supports middleware for the following operations: Aggregate. Document. Model.

What is middleware in Mongoose?

Middleware (also called pre and post hooks) are functions which are passed control during execution of asynchronous functions. Middleware is specified on the schema level and is useful for writing plugins. Mongoose 4.0 has 2 types of middleware: document middleware and query middleware.

What is pre save hook?

It might be obvious, but a pre-save hook is middleware that is executed when a document is saved.


2 Answers

It turns out that the "init" event/hook is not fired when creating a new Model, it is only fired, when loading an existing model from the database. It seems that I should use the pre/validate hook instead.

like image 113
ragulka Avatar answered Oct 20 '22 11:10

ragulka


I have successfully used middleware like MySchema.post('init', function() { ... }); with Mongoose which is then executed for each model instance loaded in a find query. Note that there isn't a next parameter to call with this middleware, it should just return when done.

like image 20
JohnnyHK Avatar answered Oct 20 '22 11:10

JohnnyHK