Undefined virtual field mongoose when using arrow function

Viewed 207

I am new to mongoDB.

this is my schema:

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

Everything is fine till here.But now I wanted to create a virtual property and hence did this:

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

But this returns undefined because this is empty. But when I use the normal function keyword to create the function it solves the issue. Doesnt the arrow function bind this ?

2 Answers

this is happening because you are using ES6 arrow function which can't bind 'this' because 'this' is already bound. more on this topic here => Understanding "this" in javascript with arrow functions

try the same with normal function keyword like the following

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

enter image description here

In JavaScript ES6. Arrow Function do not have context. The this keyword points to the window object. use function name(){} if you want use this keyword

Related