[英]Mongoose Post Hook for create() rather than 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.也许我误解了,但我能找到的所有东西都可以在 mongoose model 上为
create()
提供 post hook 来代替update()
方法。 Are create()
and update()
the same? create()
和update()
是一样的吗?
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.我想要做的是在创建
User
文档时,发送欢迎 email,而不必在创建用户的每个路由/控制器上手动调用该方法。
I understand a little about pre- and post- hooks, and I have a pre-remove hook:我对 pre-hook 和 post- hooks 有一点了解,并且我有一个 pre-remove hook:
userSchema.pre('remove', async function() {
for (let response of this.responses) {
Response.findByIdAndRemove(response);
};
});
But I can't find anything within mongoose docs for a post-hook for create()
.但我在 mongoose 文档中找不到
create()
的后挂钩的任何内容。
If create()
and update()
are the same, what stops this welcome email from being sent any time the user's information is changed?如果
create()
和update()
相同,那么在用户信息发生更改时,什么会阻止发送此欢迎 email? I only want this to send once, at the very beginning.我只想在开始时发送一次。
Let me know if I'm clear as mud让我知道我是否清晰如泥
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最后,我通过 github 功能请求在 ZCCADCDEDB567ABAE643E15DCF0974E503Z 文档中找到了答案:
schema.queue
: http#html/mongoose_Schema.quedocs
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:因此,我定义了在实例化文档时要执行的
method
,然后像这样使用schema.queue
命令:
schema.queue('methodName',[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.暂时,我将
args
数组留空,因为它们只对自己进行操作,因此不需要 go 中的其他信息。
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.文档没有具体说明,但我假设由于声明方法看起来与声明任何 function 相同,因此可以在声明它调用的方法之前或之后调用
queue
方法,但我将其安全地放在后面.
Man, this is exciting.伙计,这很令人兴奋。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.