do not use arrow function to custom methods in mongoose
07 Oct 2016This bug is about this reference, so let me show code to you
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
var userSchema = new mongoose.Schema({
email: {
type: String,
unique: true,
required: true
},
name: {
type: String,
required: true
},
hash: String,
salt: String
});
userSchema.methods.setPassword = (password) => {
this.salt = crypto.randomBytes(16).toString('hex');
this.hash = crypto.pbkdf2Sync(password, this.salt, 1000,64, 'sha512').toString('hex');
};
In this case, this
will refer to setPassword
method, but userSchema, so you just have two ways can fix it
- pass
userSchema
to function - using normal function(not arrow function)
to pass userSchema
in everywhere is too inconvenient, so just use normal function to fix it, and thank ECMA.