mongoose how to handle password encoding nicely?
You DO have access to other properties from within the setter with the use of the this
keyword. For example:
userSchema.path('pass').set(function(v) { console.log(this); // Returns model instance return v;});
However, setters are unfit for your use case. As you probably know, HMAC-SHA1 is super expensive and therefore will block unless performed asynchronously. Mongoose setters require the function to return a value and there is no way to route the result of crypto.pbkdf2()'s callback to the return value of the setter function. This is a limitation of asynchronous javascript and not Mongoose itself: you can't wrap an async call within a sync function, as this destroys the nature of the async chain.
Setters are most widely used for simple string manipulations and data sanitization.
Here is a demo for encryption using only instance methods:
// Model methoduserSchema.methods.hashPassword = function(pass, callback) { // Generate salt (this should probably be async too) var salt = this.salt = crypto.createHash('md5').update(Math.random().toString()).digest('hex'); // Salt and Hash password crypto.pbkdf2(pass, salt, 25000, 512, callback);});// Implementationvar user = new User({ email: req.body.email});user.hashPassword(req.body.pass, function(err, hash){ user.pass = hash; user.save();});