Nb. This is driving me a little nuts and I\'ve been around the houses a few times. However I\'m fairly new to ES6 and JS as a whole and fully understand that a
You aren't getting a proper this
pointer in your method.
Change this line of code:
app.post('/api/v1/user/update', urlencodedParser, user.update);
to this:
app.post('/api/v1/user/update', urlencodedParser, user.update.bind(user));
When you pass user.update
, all it passes is a reference to the update()
method and the associate with the user
object is lost. When Express then calls it as a normal function, this
will be undefined
(in strict mode) inside that method rather than your user
object. You can use .bind()
to solve this issue as shown above.
FYI, this has nothing specifically to do with Express. It's a generic issue when passing a reference to an obj.method
as a callback that you want some code to store and then call later. You have to "bind" the object to it so that it gets called with the right object context.