为什么这个代码运行良好:
schema.statics.findByName = function (name) {
return this.findOne({ username: name });
};
但当我尝试这个时
schema.statics.findByName = (name) => {
return this.findOne({ username: name });
};
调用User.findByName(username)
时出现TypeError: this.findOne is not a function
错误
这个问题与mongoDB和mongoose无关。为此,我们首先需要了解JavaScript中普通函数和箭头函数之间的区别。
与常规函数相比,箭头函数中对"this"的处理有所不同。简言之,对于箭头函数,不存在此绑定。
在常规函数中,this关键字表示调用函数的对象,可以是窗口、文档、按钮或其他任何对象。
对于箭头函数,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