Mongoose: Schema statics method context(this) is empty when using es6 arrow function

Created on 9 Mar 2017  路  2Comments  路  Source: Automattic/mongoose

Environment
mongoose: v4.8.6
node: v6.10.0
MongoDB: 3.0.4

The context/this is an empty object when using arrow function to define a schema statics method, for examle

schema.statics.someMethod = (param1) => {
  console.log(this); // {}
  console.log(this.find) // undefined
}

After changing to es5
schema.statics.someMethod = function(param1) {
  console.log(this); // Not an empty object
  console.log(this.find) // [find: Function]
}

And I think it works the same way as schema.method

Most helpful comment

Do not use fat arrow syntax for model statics/methods/virtuals. Remember that fat arrow syntax has no lexical scope so you cant use .bind() and such.

All 2 comments

Try setting your static this way, without the fat arrow?

/**
 * Statics
 */
UserSchema.statics = {
  /**
   * Get user
   * @param {ObjectId} id - The objectId of user.
   * @returns {Promise<User, APIError>}
   */
  get(id) {
    return this.findById(id) // this is is defined
      .select('-password')
      .exec()
      .then((user) => {
        if (user) {
          return user;
        }

        const err = new APIError('No such user exists!', httpStatus.NOT_FOUND);
        return Promise.reject(err);
      })
      .catch((err) => Promise.reject(err));
  }
}

Do not use fat arrow syntax for model statics/methods/virtuals. Remember that fat arrow syntax has no lexical scope so you cant use .bind() and such.

Was this page helpful?
0 / 5 - 0 ratings