使用箭头函数时未定义的虚拟字段猫鼬

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
    }
})

在 here.But 之前一切都很好,现在我想创建一个虚拟 属性,因此这样做了:

//virtual property
userSchema.virtual('fullName').get(()=>{
    console.log("first name " + this.firstName);
    return this.firstName + " " + this.lastName;
});

但是thisreturnsundefined因为this是空的。 但是当我使用普通的 function 关键字创建函数时,它就解决了这个问题。 arrow 函数不绑定 this 吗?

发生这种情况是因为您正在使用无法绑定 'this' 的 ES6 箭头函数,因为 'this' 已经绑定。有关此主题的更多信息,请点击此处 => Understanding "this" in javascript with arrow functions

尝试使用普通函数关键字,如下所示

userSchema.virtual('fullName').get(function () {
  console.log("first name " + this.firstName);
  return this.firstName + " " + this.lastName;
});

在 JavaScript ES6 中。箭头函数没有上下文。 this 关键字指向 window 对象。如果您想使用 this 关键字

,请使用 function name(){}