Mongoose Post Hook for create() 而不是 update() [英] Mongoose Post Hook for create() rather than update()

查看:34
本文介绍了Mongoose Post Hook for create() 而不是 update()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

也许我误解了,但是我能找到的所有东西都可以在 mongoose 模型上为 create() 设置一个 post 钩子,而是使用 update() 方法.create()update() 是否相同?

Maybe I'm misunderstanding, but everything I can find for having a post hook for create() on a mongoose model brings up the update() method instead. Are create() and update() the same?

我想要做的是在创建 User 文档时,发送欢迎电子邮件,而不必在每个创建用户的路由/控制器上手动调用该方法.

What I want to do is when a User document is created, send a welcome email, without having to manually call the method on every route/controller that creates a user.

我对 pre- 和 post- 钩子有一点了解,而且我有一个 pre-remove 钩子:

I understand a little about pre- and post- hooks, and I have a pre-remove hook:

userSchema.pre('remove', async function() {
    for (let response of this.responses) {
        Response.findByIdAndRemove(response);
    };
});

但是我在 mongoose 文档中找不到任何关于 create() 的 post-hook 的内容.

But I can't find anything within mongoose docs for a post-hook for create().

如果create()update() 是相同的,什么会阻止在用户信息更改时发送此欢迎电子邮件?我只希望在开始时发送一次.

If create() and update() are the same, what stops this welcome email from being sent any time the user's information is changed? I only want this to send once, at the very beginning.

让我知道我是否干净如泥

Let me know if I'm clear as mud

推荐答案

我终于在 Mongoose 文档中通过 github 功能请求以迂回的方式找到了答案:schema.queue: http://mongoosejs.com/docs/api.html#schema_Schema-queue

I found the answer, finally, in the Mongoose docs in a roundabout way through a github feature request: schema.queue: http://mongoosejs.com/docs/api.html#schema_Schema-queue

所以我定义了我想在文档实例化时执行的 method(s),然后像这样使用 schema.queue 命令:

So I define the method(s) that I want to execute at the time the document is instantiated, then just use the schema.queue command like so:

schema.queue('methodName',[args]);

暂时,我将 args 数组留空,因为它们只对自己进行操作,因此不需要输入其他信息.

For the time being, I left the args array empty because they're only operating on themselves, so no other information needs to go in.

文档没有具体说明,但我认为由于声明方法看起来与声明任何函数相同,queue 方法可以在声明它调用的方法之前或之后调用,但我小心翼翼地把它放在了后面.

The docs don't say it specifically, but I would assume since declaring methods looks to be the same as declaring any function, the queue method can be called before or after declaring the method it calls, but I played it safe and put it after.

伙计,这太令人兴奋了.

Man, this is exciting.

这篇关于Mongoose Post Hook for create() 而不是 update()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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