Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Easiest way to set up a post-find transformation hook in Mongoose

I am new to Mongoose and have been given a project to extend. I quickly grasped the concept of pre and post hooks, but was wondering why there are no such hooks for find, but only for save and delete. What would be the easiest way to set up some transformations on the retrieved objects? Of course, I want to do this at the model level, and not do it every time I retrieve some objects.

I found this plugin: https://www.npmjs.com/package/mongoose-post-find and I think it will do the job well, but since I am quite new to MongoDB, I wanted to ask here, to be sure that I won't end up in performance problems.

like image 343
Preslav Rachev Avatar asked Feb 05 '15 08:02

Preslav Rachev


1 Answers

That's what the 'init' hook is for; it's executed on each doc loaded by a find query.

schema.post('init', function (doc) {
    // Transform doc as needed here.  "this" is also the doc.
});

It's only briefly mentioned in the middleware docs for some reason.

like image 122
JohnnyHK Avatar answered Sep 30 '22 09:09

JohnnyHK