没有在mongoose中调用pre函数

时间:2017-05-16 10:55:47

标签: node.js mongodb mongoose mongoose-schema

我正在尝试使用mongoose和mongodb在注册时加密密码,但根本不会调用pre函数。

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===========================//

pre功能中,根本不会打印console.log('pre called');。我在这里缺少什么?

1 个答案:

答案 0 :(得分:0)

这可能是解决您的错误的方法。

const patients = new Patients({
    username: req.body.username,
    password: req.body.password
})

if(!patients) return res.json(patients)
patients.save((err,patients) => {
    if(err) return res.json({status: 500, message: err})
    return res.json({status: 200, user: patients})
})

谢谢。