undefined value being returned by a mongoose schema function

I'm working on a method to validate a user's password using bcrypt.compare(). See the code snippet below for details.

UserSchema.methods.validatePassword = async (data) => {
  console.log(this.email); // returns undefined
  console.log(this.first_name); // returns undefined
  return await bcrypt.compare(data, this.password);
};

Below is the UserSchema that I have defined:

const UserSchema = mongoose.Schema(
  {
    email: {
      type: String,
      required: true,
      unique: true,
    },
    password: {
      type: String,
      required: true,
    },
  },
  { timestamps: { createdAt: 'created_at', updatedAt: 'updated_at' } }
);

While accessing this.password with my schema in .pre('save', ..) it works, but it returns undefined when used in schema methods. :(

Here is how the method is implemented:

const verifySignIn = async (req, res, next) => {
  const { email, password } = req.body;
  try {
    const user = await User.findOne({ email });
    if (!user) {
      return res.status(404).json({
        status: 'failed',
        message: 'User Not found.',
      });
    }
    const isValid = await user.validatePassword(password);
    if (!isValid) {
      return res.status(401).send({
        message: 'Invalid Password!',
        data: {
          user: null,
        },
      });
    }
    next();
  } catch (err) {
    Server.serverError(res, err);
  }
};

Answer №1

section, it mentions that in the official guide, it is advised not to use ES6 arrow functions when declaring methods. This is because arrow functions do not allow binding of 'this', which means that the method will not have access to the document. So, in order to resolve this issue, simply change
UserSchema.methods.validatePassword = async (data) => {...
to
UserSchema.methods.validatePassword = async function(data) {...

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

Sending PHP form data to Google Chart via AJAX

After creating a PHP form drop-down list of table names in a database that captures the user's selection, I aim to use that selected table name to generate a Google chart. However, I'm encountering difficulties in passing the variable through AJA ...

Is there a way to upload images or PDFs in a MERN project using the fetch API and save them in a specific folder within

I am encountering an issue while attempting to incorporate a new input field for adding files/images during user registration, with the intention of saving the image name in MongoDB and storing the image in a designated folder. Unfortunately, I am facing d ...

Show the document field in MongoDB following the execution of the aggregate query

Here is a sample of a data document: { "_id" : ObjectId("5f437e7846103b2ad0fc5d7d"), "order_no" : "O-200824-AGFJDQW", "shipment_no" : "S-200824-AGWCRRM", "member_id" : 22 ...

Managing duplicate primary keys in JavaScript applications can be accomplished through various patterns and techniques

I am currently utilizing the npm sequelize library to manage storage utilizing MySQL. The primary key is the Task id, which is generated using the shortid library. What would be an effective Javascript pattern to handle duplicate ids in the rare case that ...

Is utilizing a standardized logging system considered a best practice for a node and express application?

I am currently working on a node.js application that consists of several dozen modules and uses bunyan for logging with JSON output and multiple configurable streams. I have been searching for good examples on how to implement a logger instance across all ...

Effortless method for distributing NPM-loaded modules among various Browserify or Webpack bundles

Feeling frustrated trying to find a straightforward way to share code, required via NPM, across multiple Browserify or Webpack bundles. Is there a concept of a file "bridge" that can help? I'm not concerned about compile time (I know about watchify), ...

Converting Javascript Variables into a PHP Script

After noticing that the same question was being asked repeatedly, I delved into thorough research to discover effective methods for transferring a couple of JavaScript variables to a PHP script. Include data in a form as hidden values Send to URL, like & ...

A guide on implementing a .click function with jQuery

I have a code snippet that is supposed to add 100 to a number in a MySQL table when a button is clicked. However, the code does not work as expected. When I click the button, nothing happens, but if I refresh the page, it adds 100 to the number. Can some ...

Error: The JQUERY autocomplete is throwing an uncaught type error because it cannot read the property 'length' of an undefined value

These scripts are being utilized at this source I have implemented jQuery Autocomplete to search for users in my database. Below is the controller code returning Json: public function searchusers1() { if ($_GET) { $query = $this -> input ...

Jquery click event functioning on one page but malfunctioning on another

On one page, the dropdown click function is working, but on another page, even though it's the same component and JavaScript file, it's not working. Here's the component: <li class="nav-item dropdown"> <a clas ...

Using Heroku to deploy NodeJS applications

I am facing an issue while trying to deploy my NodeJS project on Heroku. The project is a multiplayer game where, locally, both players enter the same map successfully. However, on Heroku, I am unable to get both players on the same map. Below is a snippe ...

Is there a way to retrieve a singular value from various select options sharing the same name within a single form?

I am facing an issue with my code where only the value assigned to the last select option panel is being saved in the database table. I need assistance as it was working well initially but for some reason, it's not functioning correctly now. <?php ...

Having trouble with Typescript accurately converting decimal numbers?

I am struggling with formatting decimals in my Typescript class. export myclass { deposit: number; } After converting my web API class to this Typescript class, my decimal amounts lose their additional zero. For example, 1.10 becomes 1.1. I want to keep ...

Utilizing various methods of interaction in asp.net

Imagine I have two webpages, namely page1.aspx and page2.aspx. The scenario is as follows: in page1.aspx, I use window.open() in JavaScript to call page2.aspx and pass a query string. Then, in page2.aspx (the child page), I need to gather user informatio ...

Merge the chosen values from the drop-down menu into one string

Any suggestions would be greatly appreciated! I am currently developing an application using ASP.NET web forms that consists of a dropdown list and two list boxes. I want these elements to be cloned whenever a specific button is clicked. However, my issue ...

Locate specific phrases within the text and conceal the corresponding lines

I have a JavaScript function that loops through each line. I want it to search for specific text on each line and hide the entire line if it contains that text. For example: <input id="search" type="button" value="Run" /> <textarea id ...

What is the procedure for obtaining an Observable for an Event?

How can I obtain an Observable of an Event in Angular 2? For instance, is it possible to subscribe to a click event but only trigger after two clicks? Can we create an Observable of MouseClick event objects? If I want to filter by button or ctrlKey, or h ...

Producing numerous results from a single input

How can I ensure that users input their address correctly, including street, number, entrance, floor, and apartment, into a single form field without missing any of the values? Additionally, how can I then extract each value (street, number, entrance, floo ...

What improvements can be made in the MongoDB structure for a more efficient package or wallet system?

I am currently developing a package/wallet system that involves multiple users. Within my mongodb database, I have organized the data into 4 collections: Business const businessSchema = new mongoose.Schema({ name: { type: String, unique: true }, . ...

NodeJS hit with ECONNREFUSED error while trying to run localhost server

I currently have a NodeJS server running on my local machine, listening to port 50000. I am trying to make a simple GET request to this server from another local server, but I keep receiving an ECONNREFUSED error message: { Error: connect ECONNREFUSED 127 ...