簡體   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