Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Pre save hook doesn't provide document #3333

Closed
ghost opened this issue Sep 2, 2015 · 3 comments
Closed

Pre save hook doesn't provide document #3333

ghost opened this issue Sep 2, 2015 · 3 comments

Comments

@ghost
Copy link

ghost commented Sep 2, 2015

There is a problem with the pre save hook where 'this' should give me the document being saved but it gives undefined instead.

import mongo from 'mongoose'
import crypt from 'bcryptjs'

const User = new mongo.Schema({
  username: {type: String, unique: true, required: true},
  password: {type: String, select: false, required: true}
  // token: {type: String}
})
//
User.pre('save', (next) => {
  console.log(this);
  if (this.isModified('password') || this.isNew) {
    crypt.genSalt(10, (err, salt) => {
      if (err) {
        next(err)
      } else {
        crypt.hash(user.password, salt, (err, hash) => {
          if (err) {
            next(err)
          } else {
            user.password = hash
            next()
          }
        })
      }
    })
  } else {
    next()
  }
})

export default mongo.model('User', User)

What could possibly be the error?
P.S.: It saves normally when the pre hook being is not used.

@vkarpov15
Copy link
Collaborator

Fat arrow in ES6 binds this to the lexical scope, which is just a fancy way of saying that this inside an arrow function is the same as outside the arrow function. Use User.pre('save', function(next) {}); instead.

@ghost
Copy link
Author

ghost commented Sep 2, 2015

Is there a way to get the object with the arrow function?, I would use the 'function' but a style guide is imposed in the project.

@vkarpov15
Copy link
Collaborator

Unfortunately not atm, pre hooks explicitly rely on passing the document through this rather than as a parameter. Fat arrows won't work with this paradigm.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant