These are chat archives for Automattic/mongoose

24th
May 2018
Damián Adams
@do-adams
May 24 2018 00:17

Hey guys.

I’m having trouble with adding a static method to a schema. In my case I’ve defined a userSchema and then added a static method through statics, but when I debug the code it throws an error when I attempt to access this inside the static method; apparently this is undefined at run-time :

userSchema.statics.deserializeUser = function(id, done) {
    this.findById(id, function(err, user) {
        return done(err, user);
    });
};

According to the docs I don’t think this should happen. I can write this logic elsewhere so it’s not a biggie but this does concern me as it should be working AFAIK.

Kev
@lineus
May 24 2018 00:18
@do-adams how are you calling deserializeUser() ?
Damián Adams
@do-adams
May 24 2018 00:18
In the user.js file I do add the static method before creating the model with mongoose.model(‘User’, userSchema) so it’s definitely not that.
Kev
@lineus
May 24 2018 00:19
is your actual code in your module an arrow function by chance? or is it a common function like your example above?
Damián Adams
@do-adams
May 24 2018 00:19
It’s for using it with Passport in an Express application. But now that you mention it, it might be possible that Passport is de-binding it or something crazy like that.
I’ll test it outside of that (main) use case and let you know! And no, no arrows >:)
Kev
@lineus
May 24 2018 00:22
I figured it wouldn't be that easy :+1:
Damián Adams
@do-adams
May 24 2018 00:32

Yeah that was it, @lineus ! It was just a JS thing ™.

This fixed it:

userSchema.statics.deserializeUser = function() {
    return (function(id, done) {
        this.findById(id, function(err, user) {
            return done(err, user);
        });
    }).bind(this);
};