1

Why is this code works fine:

schema.statics.findByName = function (name) {
  return this.findOne({ username: name });
};

But when I try this one

schema.statics.findByName =  (name) => {
  return this.findOne({ username: name });
};

I get TypeError: this.findOne is not a function error when call User.findByName(username)

BANTYC
  • 151
  • 1
  • 9
  • See https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-inside-a-callback/20279485#20279485 and https://stackoverflow.com/questions/2236747/what-is-the-use-of-the-javascript-bind-method – Mickael B. May 02 '20 at 15:41

1 Answers1

1

Well, this issue is not related to mongoDB and mongoose. For this, first we need to understand the difference between normal function and arrow functions in JavaScript.

The handling of "this" is different in arrow functions compared to regular functions. In short, with arrow functions there are no binding of this.

In regular functions the this keyword represented the object that called the function, which could be the window, the document, a button or whatever.

With arrow functions, the this keyword always represents the object that defined the arrow function. They do not have their own this.

let user = { 
name: "Stackoverflow", 
myArrowFunc:() => { 
    console.log("hello " + this.name); // no 'this' binding here
}, 
myNormalFunc(){        
    console.log("Welcome to " + this.name); // 'this' binding works here
}
};

user.myArrowFunc(); // Hello undefined
user.myNormalFunc(); // Welcome to Stackoverflow
Kapil Raghuwanshi
  • 867
  • 1
  • 13
  • 22