Reputation: 740
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?
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.
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);
};
});
But I can't find anything within mongoose docs for a post-hook for create()
.
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
Upvotes: 0
Views: 3707
Reputation: 740
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
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]);
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.
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.
Upvotes: 7