When I use following code:
userSchema.pre('save', (done) => {
if(this.isModified('password')) {
bcrypt.hash(this.password, null, null, (err, hash) => {
if(err) return next(err);
this.password = hash;
this.updated_at = new Date().toISOString();
done();
});
} else {
return done();
}
});
I receive following Error:
TypeError: this.isModified is not a function
at model.userSchema.pre (C:\code\project\core\models\user.js:26:11)
at _next (C:\code\project\node_modules\hooks-fixed\hooks.js:62:30)
at fnWrapper (C:\code\project\node_modules\hooks-fixed\hooks.js:186:8)
at model.Object.defineProperty.value.fn (C:\code\project\node_modules\mongoose\lib\schema.js:221:11)
at _next (C:\code\project\node_modules\hooks-fixed\hooks.js:62:30)
at fnWrapper (C:\code\project\node_modules\hooks-fixed\hooks.js:186:8)
at C:\code\project\node_modules\mongoose\lib\schema.js:196:17
at C:\code\project\node_modules\kareem\index.js:127:16
at _combinedTickCallback (internal/process/next_tick.js:67:7)
at process._tickCallback (internal/process/next_tick.js:98:9)
Problem:
this
is not a Document, Query or Schema. It's value is {}
How can I solve that?
You are using an arrow operator for the callback, which changes the scope of this
. If you define a regular callback you should be fine, e.g.:
userSchema.pre('save', function(done) {
});
Ok. Thanks. It works.
Fix your eslintrc
On Tue, Nov 29, 2016 at 5:16 AM, Nick Rameau notifications@github.com
wrote:
Is there a way to do it with arrow functions? I'm using ES6 and my
eslintrc is complaining about regular callbacks.—
You are receiving this because you are subscribed to this thread.
Reply to this email directly, view it on GitHub
https://github.com/Automattic/mongoose/issues/4537#issuecomment-263567210,
or mute the thread
https://github.com/notifications/unsubscribe-auth/ABi5KbZG27HnF2sX2RwDIhTp4Rz1lIG_ks5rDCW1gaJpZM4J_8-c
.
I had this issue, as well. Thanks for help @VictorGerritsenQLVR!
Is there a way to change the code to accommodate the arrow operator, rather than using function(next)
?
@domarp-j Good question. I thought about it and tried to figure it out but I couldn't come up with anything easier than just switching to a regular callback function. Maybe someone else has done it tho. I'll keep an eye on this issue.
No way to do it, fat arrows use lexical scope for context, no way around it.
had same issue, thanks for the help
Hi, was stuck on the same problem with the es6 arrow function. Thank you very much!
great thank u
Thanks, works for me too.
Most helpful comment
You are using an arrow operator for the callback, which changes the scope of
this
. If you define a regular callback you should be fine, e.g.: