Search code examples
node.jsmongoosepassport.jsmongoose-schemapassport-local

how to change username password using passport local mongoose


i'm trying to change the password of username using local mongoose 

i tried to use setPassword function but it does not seem to work

router.put('/admin/users/:username', function(req,res){
User.findByUsername.then(function(sanitizedUser){
    if (sanitizedUser){
        sanitizedUser.setPassword(req.body.password, function(){
            sanitizedUser.save();
            res.redirect("back");
        });
    } else {
        res.redirect("back");
    }
},function(err){
    console.error(err);
})
});

is there any other solution other than setpassword what exactly i did wrong?


Solution

  • I have posted what I tend to do to reset password (part of it includes hashing it but the rest is the same). Except I am using async/await

    const { password } = req.body;
    
    let restP = new User();
    
        try {
          const newP = await restP.generateHash(password.password);
    
          const resetP = await User.findByIdAndUpdate(
            req.params.id,
            { $set: { passwordHash: newP } },
            {
              fields: { passwordHash: 0 },
              new: true
            }
          )
    
    
          // return image user object
          res.send(resetP);
        } catch (error) {
          console.log(error);
          return res.status(400).send(error);
        }