BANTYC
BANTYC

Reputation: 163

Mongoose schema. Statics is not a function

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)

Upvotes: 1

Views: 516

Answers (1)

Kapil Raghuwanshi
Kapil Raghuwanshi

Reputation: 877

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

Upvotes: 1

Related Questions