简体   繁体   中英

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?

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');
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM