Search code examples
node.jsmongodbmongoosemongoose-middleware

why do i have to use next() in mongoose pre save middleware


userschema.pre('save',async function(next){
    const user =this;
    
    if(user.isModified('password')){
        user.password=await bcrypt(user.password,8)
    }

    next()
})

i am first time using pre save middleware and getting a bit confusion in it

i saw the mongoose guide for middleware but i still don't understand why we have to declare next in func param and use it in the end of function, what i think is its make sure that all statements got executed before saving the model but i'm not sure can anyone explain it to me please


Solution

  • The next keywork refer to the next middleware that will run after yours to process the request. In the end of your function, you call next() to pass the control to the next middleware.

    Something like, "Hey, I've done my job for this request. I give it to you, do your job" :)