Tuesday 16 May 2017

pre function not called in mongoose

I am trying to encrypt password on registration using mongoose and mongodb but pre function is not called at all.

var mongoose = require('mongoose');
var Schema = mongoose.Schema,
    bcrypt = require('bcrypt'),
    SALT_WORK_FACTOR = 10;


var patientSchema = new Schema({
    username: {type: String, trim: true, index: { unique: true }},
    password: {type: String, required: true}
});

//====================== Middleware:Start==========================//
patientSchema.pre('save', function(next) {
    console.log('pre called'); //This is not printed at all
    var user = this;

    // only hash the password if it has been modified (or is new)
    if (!user.isModified('password')) return next();

    // generate a salt
    bcrypt.genSalt(SALT_WORK_FACTOR, function(err, salt) {
        if (err) return next(err);

        // hash the password along with our new salt
        bcrypt.hash(user.password, salt, function(err, hash) {
            if (err) return next(err);

            // override the cleartext password with the hashed one
            user.password = hash;
            next();
        });
    });
});
//======================Middleware:End===========================//

//======================API Routes:Start===========================//
router.route('/signup')
        .post(function (req, res) {
            console.log('post signup called', req.body);
            var patients = new Patients({
                username: req.body.username,
                password: req.body.password
            });

            Patients.findOne({username: req.body.username}, function (err, user) {

                if (err) {
                    console.log('user not found');
                }

                if (user) {
                    console.log("patient already exists");
                    res.json({message: 'patient already exists'});
                } else {
                    //Saving the model instance to the DB
                    patients.save(function (err) {
                        if (err)
                            throw err;
                        console.log("user Saved Successfully");
                        res.json({message: 'user Saved Successfully'});
                    });
                }

            });

        });

module.exports = router;
//======================API Routes:End===========================//

Inside the pre function, console.log('pre called'); is not printed at all. What am I missing here?



via kittu

No comments:

Post a Comment