繁体   English   中英

Mongoose 架构。 静力学不是 function

[英]Mongoose schema. Statics is not a function

为什么这段代码可以正常工作:

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 无关。 为此,首先我们需要了解普通的function和JavaScript中的箭头函数的区别。

与常规函数相比,箭头函数对“this”的处理是不同的。 简而言之,箭头函数没有 this 的绑定。

在常规函数中,this 关键字代表 object,它调用 function,可以是 window、文档、按钮或其他。

对于箭头函数,this 关键字始终表示定义箭头 function 的 object。 他们没有自己的这个。

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