Jacob Jacob - 4 months ago 14
Node.js Question

Mongoose schema methods and "this" updating properties - NodeJS



In my

usersSchema
I want to set a hashed password to my
hash
field. The schema looks like 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 my route, I am trying to set a new user with a name, email, and password. Here's the 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 I
console.log(user)
from the route, it gives me the following:
{ name: 'Jacob', email: 'jacob@gmail.com' }

I know that the
setPassword
method works as far as creating proper hashes. It does not, however, save those hashes to the
user
object. How do I apply
setPassword
to the
user
object that calls it so that it can set the
salt
and
hash
properties?

Answer

By using the fat arrow notation, you're changing what this is referring to in setPassword, so it's not pointing to the user document anymore.

Try using a 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