在 Mongoose 中设置 post-find 转换挂钩的最简单方法 [英] Easiest way to set up a post-find transformation hook in Mongoose

查看:45
本文介绍了在 Mongoose 中设置 post-find 转换挂钩的最简单方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Mongoose 的新手,已经获得了一个要扩展的项目.我很快掌握了 pre 和 post 钩子的概念,但想知道为什么 find 没有这样的钩子,而只有 savedelete.在检索到的对象上设置一些转换的最简单方法是什么?当然,我想在模型层面做这个,而不是每次检索一些对象时都这样做.

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.

我找到了这个插件:https://www.npmjs.com/package/mongoose-post-find 并且我认为它可以很好地完成这项工作,但是由于我对 MongoDB 很陌生,所以我想在这里问一下,以确保我最终不会遇到性能问题.

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.

推荐答案

这就是 'init' 钩子的用途;它在 find 查询加载的每个文档上执行.

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.

这篇关于在 Mongoose 中设置 post-find 转换挂钩的最简单方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆