Having trouble with the mongoose virtual field being undefined while using an arrow function?

Hey, I'm exploring the world of mongoDB!

Here's the schema I created:

const userSchema = new mongoose.Schema({
    firstName:{
        type:String,
        required:true,
        trim:true,
        min:3,
        max:20
    },
    lastName:{
        type:String,
        required:true,
        trim:true,
        min:3,
        max:20
    }
})

All good till this point. But now I wanted to add a virtual property, so I tried this out:

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

However, this was returning undefined as it was empty. Interestingly, when I switched to using the traditional function keyword, the issue was resolved. Aren't arrow functions supposed to bind this? Why did it not work in this case?

Answer №1

The issue at hand arises due to the utilization of ES6 arrow functions, which are unable to bind this. Essentially, this is already bound.

For further insight on this matter, please refer to: Understanding "this" in javascript with arrow functions

Consider employing regular function keywords instead, as illustrated below

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

https://i.sstatic.net/yRgZk.png

Answer №2

When it comes to JavaScript ES6, Arrow Functions lack context. The keyword this specifically refers to the window object. To utilize the this keyword, it is recommended to use the syntax function name(){}.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is the behavior of undefined different in Chrome?

Upon examining my Asp masterpage, I noticed the following code snippet: <script> if (theForm !== undefined) { // <<== line 746: error theForm.onsubmit = ...bla bla... ; } </script> When checking the Chrome console, an er ...

Using Vue.js, perform calculations on various fields within an array of objects generated by the v-for directive

I am currently learning Vue.js and I have implemented a v-for loop to iterate through an array of objects. However, I now need to calculate a specific field (precoPorKg) within this loop. In order to perform this calculation, the input item.quantidade mus ...

Leveraging the power of JavaScript to retrieve data from PHP/MySQL

Considering creating an Android app using Appcelerators Titanium application and have a question. The website for the app is built with PHP/MySQL, and I'm curious if it's possible to dynamically pull data from the database using JavaScript in Tit ...

Creative Blueprint

Our company currently operates 3 browser based games with a team of just 4-5 coders. We are looking to enhance the collaboration within our coding team and streamline our processes. Considering the fact that our games are built using a mix of html, php, j ...

Redux-form fails to retrieve the value of the SelectField

I'm trying to work with a simple form using react and redux-form. My goal is to gather all the field values from my form and send them to my RESTful API using jQuery ajax. Unfortunately, I've run into an issue where redux-form doesn't seem ...

Is it possible for Penthouse to retrieve critical CSS while using javascript?

I am currently utilizing the laravel-mix-criticalcss npm package to extract the critical CSS of my website. This package leverages Penthouse under the hood, and you can configure Penthouse settings in your webpack.mix.js within the critical options. The ...

Loading the central portion exclusively upon clicking a tag

Is there a way for websites to load only the middle section of the page when a link (a-tag) is clicked? I understand this is typically done through AJAX, but how does it update the URL to match the href in the a tag? I've tried using the .load functi ...

Utilizing the W3Schools CodeColor library across various elements

Looking to provide code examples using a JS code highlighter with an ID? Check out this URL for a demonstration: https://www.w3schools.com/howto/tryit.asp?filename=tryhow_syntax_highlight Want to use this for multiple examples but finding that the ID only ...

What is the best way to access external value in an Angular directive?

check out this plunker link. HTML: <body ng-app="app"> <h1>selectable</h1> <selectable text="link1" status="true"></selectable> <selectable text="link2" status="false"></selectable> <p> ...

I encountered an error when attempting to choose an element within a webelement, receiving a message stating that the object is

Trying to locate an element within a web element is resulting in an error message saying: "TypeError: 'WebElement' object is not callable" def get_engagmet(driver, time, a): engagment = {} body_element = driver.find_elements_by_xpath("// ...

Struggling to dynamically generate class names with clsx in combination with TailwindCss

Greetings! I am a JavaScript developer who is not very skilled yet, working with React and Next. Specifically, I am using this template When it comes to declaring component class names, I have been using a utility function that combines tailwind-merge and ...

Steps for Adding a JSON Array into an Object in Angular

Here is a JSON Array that I have: 0: {name: "Jan", value: 12} 1: {name: "Mar", value: 14} 2: {name: "Feb", value: 11} 3: {name: "Apr", value: 10} 4: {name: "May", value: 14} 5: {name: "Jun", value ...

Attempting to develop a kick command for discord using discord.js, which will initiate the kick action based on the user's

I've been trying to implement a discord kick command that specifically targets a user on my server. It may not be the most practical solution, but it's essential for my bot's functionality. Here's the code I have so far: if (command == ...

What is the encoding for Javascript in UTF-8?

My current ajax call is able to successfully send the request and retrieve the expected response. However, I am facing difficulty in correctly displaying it in li items. $.ajax({ url: "{% url 'users:profile_page_tags_get' 'primary&apos ...

Darken the entire webpage and gradually fade in a specific div element using Jquery

Currently, I am working on implementing the following functionality: - When a link is clicked, it should trigger a function to show a DIV (#page-cover) that will dim down the entire background. This div has a z-index of 999. - Following the dimming effect, ...

Uploading an image along with additional information to Strapi using React

Can you assist me with allowing users to post data on Strapi, such as their name, URL, description, and image? I attempted to add an input type file but encountered a 500 error. I suspect this could be due to the need to call localhost:1337/upload, but I& ...

Angular Bootstrap UI - Ensuring only one element collapses at a time

I have integrated the angular bootstrap UI library into my website by following this link: https://angular-ui.github.io/bootstrap/ One issue I am facing is that when I implement a collapsible feature using this library, it collapses or expands every eleme ...

Discover the `.next/server` feature on Vercel - a platform where it seamlessly operates unlike on Netlify

Having trouble accessing .next/server on Vercel when running the build:rss script: { "export": "next export", "build": "next build && npm run export && npm run build:rss", "build:rss": &q ...

Angular 8 delivers an observable as a result following a series of asynchronous requests

I am working on a simple function that executes 3 asynchronous functions in sequence: fetchData() { this.fetchUsers('2') .pipe( flatMap((data: any) => { return this.fetchPosts(data.id); }), fl ...

Employ the find() function to ascertain the result of a condition

I'm struggling to grasp how to utilize the find() method in a conditional statement. In simple terms, I want the conditional to evaluate as true if the value of item.label is equal to the value of e.target.value. if (this.props.Items.find(item => ...