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

断了今生、忘了曾经 提交于 2021-01-02 08:40:36

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!