javascript - Mongoose schema methods and "this" updating properties - NodeJS -
in usersschema
want set hashed password hash
field. schema looks this:
// models/user-model.js const usersschema = new schema({ name: { type: string, required: true }, email: { type: string, unique: true, required: true }, hash: string, salt: string }, { timestamps: true }); usersschema.methods.setpassword = (password) => { this.salt = crypto.randombytes(16).tostring('hex'); this.hash = crypto.pbkdf2sync(password, this.salt, 1000, 64).tostring('hex'); };
in route, trying set new user name, email, , password. here's route:
// routes/users.js router.get('/setup', (req, res) => { const user = new user(); user.name = 'jacob'; user.email = 'jacob@gmail.com'; user.setpassword('password'); user.save() .then((user) => { const token = user.generatejwt(); res.json({ yourtoken: token }); }) .catch((err) => { res.json(err); }); });
when console.log(user)
route, gives me following: { name: 'jacob', email: 'jacob@gmail.com' }
i know setpassword
method works far creating proper hashes. not, however, save hashes user
object. how apply setpassword
user
object calls can set salt
, hash
properties?
by using fat arrow notation, you're changing this
referring in setpassword
, it's not pointing user document anymore.
try using regular function declaration:
usersschema.methods.setpassword = function(password) { this.salt = crypto.randombytes(16).tostring('hex'); this.hash = crypto.pbkdf2sync(password, this.salt, 1000, 64).tostring('hex'); };
Comments
Post a Comment