You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
// user is an instance of Model, which are mongoose documents that have a one-to-one mapping to a record in the databaseconstuser=newSchemaModel( ... );// serial hooksuser.pre('save',function(next){// do stuffnext();});// parallel hooksuser.pre('save',true,function(next,done){// do synchronous stuff// then pass control to next middleware/DBnext();// do **a**synchronous stuffsetTimeout(done,100000);});
Use Case
removing a user from the database will remove all his post.
deleting contact could block them as well...
If there is an error that I want to propagate then pass in a new Error() to the next() function.
Then when the user doc calls save() then the error will show up in the callback/promise
user.save().then(functionfulfilled(){... }).catch(functionhandleError(error){// this is where Ill find the error passed to next()console.log(error);}
Post Hooks
no flow control (done())
can still happen in a serial fashion, by giving next() as second parameter
a save() call triggers the 'validate' hook. Note this cause all pre & post 'validate' hooks to happen before any saving to the database occurs.
user.post('save',function(doc){// Do stuff after save}// can chain them user.post('save',function(doc,next){// do stuff then pass to next post hooknext();}
Important
hooks and not triggered with update() and findOneAndUpdate()
Pre Hooks
Use Case
If there is an error that I want to propagate then pass in a
new Error()
to thenext()
function.Then when the
user
doc callssave()
then the error will show up in the callback/promisePost Hooks
save()
call triggers the 'validate' hook. Note this cause all pre & post 'validate' hooks to happen before any saving to the database occurs.Important
update()
andfindOneAndUpdate()
The text was updated successfully, but these errors were encountered: