Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

isModified and pre-save mongoose...Nodejs

Hi i want save with hashed password only if password is change, so i used isModified function in pre-save, but its always return false even i changed the password. The reason that i am trying to do this is because i dont want to change and save my password when i change other properties.

router.post('/changepw', isAuthenticated, function (req, res, next) {
    User.findOneAndUpdate({_id: req.user._id}, {$set: req.body},{ new: true }, function (err, user){

        if (err) {
          return err;
        } 
        else {

          if (req.body.password) {
            user.password = req.body.password;
            user.save();
          } else { 

          }

        }
        res.redirect('/profile');
    });
});

like here i dont want to change my password when i change my graduated value.

router.post('/edit', isAuthenticated, function (req, res, next) {
    User.findOneAndUpdate({
        _id: req.user._id
    }, {
        $set: {
            name: req.body.name,
            phone: req.body.phone,
            classc: req.body.classc,
            major: req.body.major,
            minor: req.body.minor,
            linkedin: req.body.linkedin,
            bio: req.body.bio
        }
    }, {
        new: true
    }, function (err, user, done) {

        if (err) {
            return err;
        } else {

            if (typeof req.body.graduated == 'undefined') {
                user.graduated = false;


            } else if (typeof req.body.graduated == 'string') {

                user.graduated = true;

            }

            user.save();
        }
        res.redirect('/profile');
    });
});
userSchema.pre('save', function(next) {
console.log(this.isModified('password'));                                                                                                                                        
    if(this.password && this.isModified('password')){                                                                                                                                                                                                                                                                                      
        this.password  = bcrypt.hashSync(this.password, bcrypt.genSaltSync(8),null);                                                                                                             
    }

    next()                                                                                                                                                                     
}); 

any suggestions?

like image 784
Scott Kim Avatar asked May 29 '18 10:05

Scott Kim


People also ask

What is pre save in Mongoose?

The save() function triggers validate() hooks, because mongoose has a built-in pre('save') hook that calls validate() . This means that all pre('validate') and post('validate') hooks get called before any pre('save') hooks.

Does Mongoose save overwrite?

Mongoose save with an existing document will not override the same object reference. Bookmark this question.

What are pre and post hooks?

Pre- and post-execution hooks are Processing scripts that run before and after actual data processing is performed. This can be used to automate tasks that should be performed whenever an algorithm is executed.

How do I get the Objectid after I save an object in Mongoose?

To get the object ID after an object is saved in Mongoose, we can get the value from the callback that's run after we call save . const { Schema } = require('mongoose') mongoose. connect('mongodb://localhost/lol', (err) => { if (err) { console. log(err) } }); const ChatSchema = new Schema({ name: String }); mongoose.


2 Answers

Try this

userSchema.pre('save', async function (next) {
  // Only run this function if password was moddified (not on other update functions)
  if (!this.isModified('password')) return next();
  // Hash password with strength of 12
  this.password = await bcrypt.hash(this.password, 12);
  //remove the confirm field 
  this.passwordConfirm = undefined;
});
like image 40
Mohamed Daher Avatar answered Sep 26 '22 14:09

Mohamed Daher


note that when you're using findAndUpdate() method, the pre-save hook is not triggered. Check the Mongoose documentation by using new hooks: http://mongoosejs.com/docs/middleware.html#notes.

like image 196
rphonika Avatar answered Sep 22 '22 14:09

rphonika