[英]Undefined virtual field mongoose when using arrow function
我是 mongoDB 的新手。
這是我的架構:
const userSchema = new mongoose.Schema({
firstName:{
type:String,
required:true,
//remove whitespaces
trim:true,
//minimum length
min:3,
max:20
},
lastName:{
type:String,
required:true,
trim:true,
min:3,
max:20
}
})
一切都很好,直到這里。但現在我想創建一個虛擬財產,因此這樣做了:
//virtual property
userSchema.virtual('fullName').get(()=>{
console.log("first name " + this.firstName);
return this.firstName + " " + this.lastName;
});
但this
收益undefined
,因為this
是空的。 但是當我使用普通的function
關鍵字來創建函數時,它解決了這個問題。 arrow
函數不綁定this
嗎?
發生這種情況是因為您使用的 ES6 箭頭函數無法綁定 'this',因為 'this' 已經綁定。 更多關於此主題的信息 => 使用箭頭函數理解 javascript 中的“this”
嘗試使用普通的函數關鍵字,如下所示
userSchema.virtual('fullName').get(function () {
console.log("first name " + this.firstName);
return this.firstName + " " + this.lastName;
});
在 JavaScript ES6 中。 箭頭函數沒有上下文。 this
關鍵字指向窗口對象。 如果要使用this
關鍵字,請使用function name(){}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.