简体   繁体   English

Mongoose 架构。 静力学不是 function

[英]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)调用User.findByName(username)时出现TypeError: this.findOne is not a function错误

Well, this issue is not related to mongoDB and mongoose.好吧,这个问题与 mongoDB 和 mongoose 无关。 For this, first we need to understand the difference between normal function and arrow functions in JavaScript.为此,首先我们需要了解普通的function和JavaScript中的箭头函数的区别。

The handling of "this" is different in arrow functions compared to regular functions.与常规函数相比,箭头函数对“this”的处理是不同的。 In short, with arrow functions there are no binding of this.简而言之,箭头函数没有 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.在常规函数中,this 关键字代表 object,它调用 function,可以是 window、文档、按钮或其他。

With arrow functions, the this keyword always represents the object that defined the arrow function.对于箭头函数,this 关键字始终表示定义箭头 function 的 object。 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM