Mostafa Ghadimi
Mostafa Ghadimi

Reputation: 6776

Data and salt arguments required

I'm trying to hash the password of admin in my site. I have searched and found out that this error is because of being null or undefined the value that we want to hash it.

here is my code, whenever I console.log(admin) it returns {}, I don't know why.

adminSchema.pre('save', (next) => {
    var admin = this;
    console.log(admin)
    bcrypt.hash(admin.password, 10, (err, hash) => {
        if (err) return next(err);
        admin.password = hash;
        next();
    });
});

var adminModel = mongoose.model('Admin', adminSchema);
module.exports = adminModel;

server side code:

var adminModel = require('./../models/admins');
router.post('/register', (req, res) => {
    var newAdmin = {
        adminName: req.body.adminName,
        faculty: req.body.faculty,
        email: req.body.email,
        password: req.body.password
    }

    adminModel.create(newAdmin, (err, admin) => {
        if (err) {
            console.log('[Admin Registration]: ' + err);
        }
        else {
            console.log('[Admin Registration]: Done');
            req.session.adminId = admin._id;
            res.redirect('/admin/submitScore')
        }
    })
});

Unfortunately, I can't find the reason of that the console.log(admin) is empty. I would be thankful if anyone could help me.

Upvotes: 0

Views: 2983

Answers (1)

David Stenstrøm
David Stenstrøm

Reputation: 783

The keyword this changes scope when used in arrow functions. See more here. This is not a problem in your express route, but in your mongoose middleware it is. Change your function to not use this or make an old fashioned function(){}

Upvotes: 1

Related Questions