Mongoose: Pre save hook doesn't provide document

Created on 2 Sep 2015  路  3Comments  路  Source: Automattic/mongoose

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.

Most helpful comment

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.

All 3 comments

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.

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.

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.

Was this page helpful?
0 / 5 - 0 ratings