I am trying to assign the pre handler to the mongoose save event and encrypt the document before saving:
userShecma.pre('save', function(next) {
var self = {};
self.Key = this.password;;
self.EncriptedString = encrypt.encrypt(JSON.stringify(this), this.password);
self.user = this.user
self.decrypt = function() {
var user = JSON.parse(encrypt.decrypt(this.EncriptedString, this.Key));
for(var key in user) {
this[key] = user[key];
}
}
for(var key in this){
delete this[key];
}
for(var key in self){
this[key] = self[key];
}
console.log(this);
next(self);
});
I have tried a bunch of diffrent things, sometimes I get an error, sometimes it just doesnt change the document.
Let me know if you need any more info,
Ari
EDIT: Tried Benoir's Answer, I can't edit this.
I believe calling next(self) will make the next handler think that there was an error and not save the document.
You should just call next()
Look at http://mongoosejs.com/docs/middleware.html under 'Error Handling'
I Figured It Out: Benoir's Answer + You Cannot add or remove properties to/from the document unless they are defined in the Schema.