Node.js Schema.pre('save) Is Not Changing Data
I'm making user authorization system and want to hash password before save it to DB. To reach this i use bcrypt-nodejs. The question in title above; var mongoose = require('mongoos
Solution 1:
Below the solution for your problem:
var mongoose = require('mongoose');
var bcrypt = require('bcrypt-nodejs');
var userSchema = new mongoose.Schema({
email: {
type: String,
unique:true,
required: true
},
username: {
type: String,
required: true
},
password: {
type: String,
required: true
}
});
userSchema.pre('save', function() {
console.log(this.password);
this.password = bcrypt.hashSync(this.password);
console.log(this.password);
});
module.exports = mongoose.model('User', userSchema);
Code that I used to run the solution:
exports.create = asyncfunction () {
let user = newUser({
email : 'test@test.com',
username: 'new username',
password: '123abc'
});
returnawait user.save()
.then((result) => {
console.log(result);
}).catch((err) => {
console.log(err)
});
};
Your first problem is that you can not use arrow function in this type of method: Same Error Solved
Second problem, is that you need to call the bcrypt.hashSync method, if you don‘t want to handle Promises.
And one observation about your schema, all the fields are unique. This attribute unique:true will create a index in the database, and you won't find the user by password. Here the moongose documentation: Moogose Documentation
A common gotcha for beginners is that the unique option for schemas is not a validator. It's a convenient helper for building MongoDB unique indexes. See the FAQ for more information.
Post a Comment for "Node.js Schema.pre('save) Is Not Changing Data"