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)
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.