问题
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.
回答1:
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.
来源:https://stackoverflow.com/questions/28339616/easiest-way-to-set-up-a-post-find-transformation-hook-in-mongoose