I'm struggling to resolve the issue I'm encountering with findOneAndUpdate. Can anyone offer guidance on how to

Attempting to modify a mongodb document using the findOneAndUpdate method.

Experimented with various approaches to locating the document and restructuring the update operation.

router.put(
  "/edit",
  [
    auth,
    [
      check("name", "Name is required")
        .not()
        .isEmpty(),
      check("email", "Please enter a valid email").isEmail(),
      check(
        "password",
        "Please enter a password with 8 or more characters"
      ).isLength({ min: 8 })
    ]
  ],
  async (req, res) => {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      res.status(404).json({ errors: errors.array() });
    }

    const { email, password, name } = req.body;

    const update = {
      email,
      password,
      name
     };

    const salt = bcrypt.genSalt(10);

    update.password = bcrypt.hash(password, salt);

    try {
      const user = await User.findOneAndUpdate(
        { user: req.user.id },
        { $set: update },
        { new: true, upsert: true }
      );
      res.json(user);
    } catch (err) {
      console.error(err);
      res.status(500).send("Server Error");
    }
  }
);

Desire for the updated user to be returned but consistently encountering an error leading to a 500 response.

Answer №1

The methods bcrypt.genSalt and hash return promises, so make sure to await them.

I also decided to switch from findOneAndUpdate to findByIdAndUpdate because I believe it's clearer in this scenario.

Would you like to test out this updated code?

router.put(
  "/edit",
  [
    auth,
    [
      check("name", "Name is required")
        .not()
        .isEmpty(),
      check("email", "Please enter a valid email").isEmail(),
      check(
        "password",
        "Please enter a password with 8 or more characters"
      ).isLength({ min: 8 })
    ]
  ],
  async (req, res) => {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      res.status(404).json({ errors: errors.array() });
    }

    const { email, password, name } = req.body;

    const update = {
      email,
      password,
      name
    };

    const salt = await bcrypt.genSalt(10);

    update.password = await bcrypt.hash(password, salt);

    try {
      const user = await User.findByIdAndUpdate(req.user.id, update, {
        new: true,
        upsert: true
      });
      res.json(user);
    } catch (err) {
      console.error(err);
      res.status(500).send("Server Error");
    }
  }
);

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

Issues may arise when attempting to parse AJAX responses using Javascript/JQuery AJAX

There are many posts on this topic, but I am having trouble finding the specific information I need. Here is where I am struggling: I have an AJAX request for an ID and an integer (which will be used as a margin to apply on the DOM later). This is the re ...

Setting up proxy middleware in an express application

My application is structured with a frontend server (React) serving static files and a backend server (Express). I have noticed that custom header requests trigger preflight requests, causing latency in my application. My goal is to eliminate these preflig ...

the display outcome appears fuzzy and lacks sharpness

Currently, I am engaged in prototyping and showcasing data in a 3D format using three.js (version 68). The intended outcome of the entire animation is to have a collection of colored spheres representing protons and neutrons, each colored based on a specif ...

An introduction to integrating Paged.js with Vue.js3

index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <link rel="icon" type="image/svg+xml" href="/vite.svg" /> < ...

Creating several divs with an image tag within each div individually using Jade HTML pre-processor

Check out the code snippet below: <div id="cubeSpinner"> <div class="face one"> <img src="/images/Windows%20Logo.jpg" class=""> </div> <div class="face two"> <img src="/images/Turtle.jpg" class ...

Tips for determining which site was accessed

My store is linked to a grid and when it loads, it has multiple pages. Now, I need to display the page that contains a specific value. To achieve this, I make use of store.load({params: {'file': 'file33939'}});. Despite not knowing the ...

Guide to shuffling an array with a simple click of a button

To simplify, I have an array that I would like to randomize by clicking a button. Once randomized, I want to display the first result from the array with another button. The array is currently randomized when opened in Chrome, and checking the results in t ...

Application utilizing electron technology featuring various tabbed browsing windows connecting to secure websites

Currently, I am in the process of developing my own unique version of a platform similar to using Electron technology. The objective for this app is to provide users with the ability to view multiple URLs simultaneously, such as and , through a tabbed i ...

Using v-for to show the values of an object in Vuetify

I am currently developing a function in vuejs that allows users to select tables from a database, with the columns' names automatically appearing in a v-list-item component. However, I am facing difficulty in displaying these column names effectively. ...

Delete a post if the user is no longer in the database

Currently, I am working on building an API using Node.js. Within this project, I have a post model that is linked to a user entity. My goal is to ensure that when a user is deleted, any posts connected to that user are also removed from the MongoDB databa ...

What is the Reason for Repeatedly Rebuilding Our React App to Validate Changes?

Just diving into the world of React and eager to start working with it. I followed a tutorial related to this project, where create-react-app was used to create a new React application. We're facing an issue where we have to rebuild the entire app u ...

The JavaScript function's argument is determined by the value submitted in EJS

I am currently in the process of developing an express application. One of the key features involves a drop-down menu where the selected value is sent to users.js to trigger a MongoDB query. The results of this query are then returned to the EJS template a ...

Exclude the key-value pair for any objects where the value is null

Is there a way to omit one key-value pair if the value is null in the TypeScript code snippet below, which creates a new record in the Firestore database? firestore.doc(`users/${user.uid}`).set({ email: user.email, name: user.displayName, phone: ...

django div auto refresh

Whenever I submit a form, the content of console.html is supposed to change. I tried to use the code below to refresh the page, but it doesn't seem to refresh console.html: Javascript function autorefresh() { // auto refresh page after 1 sec ...

Encountered an issue with converting value to Date using mongoose and nodejs

Feeling a bit crazy here, just can't get it to work... Here is how I defined the Schema: const ChildSchema = new Schema({ birthDate: { type: Date, required: true } }); And here is the parent Schema: const ParentSchema = new Schema( { ...

Leveraging the "while True" loop for processing http requests in Python

My goal is to populate a MongoDB collection with all the articles (JSON objects of the requests result) from an API known as "Spaceflight News". I understand that the code I have is quite basic, but I'm looking for a more elegant or correct alternati ...

Javascript doesn't allow for the subtraction of values

Hey there! I'm currently working on enhancing a nutrition label that I've created by adding data to it. The label includes information such as fat, carbs, protein, and more. I have set up a database structure with fields like: ingName: .... fat: ...

Searching for elements in JavaScript using dynamic find control

Is there a way to implement this in JavaScript using dynamic addressType? let addressType = "bar"; document.getElementById('<%= this.FindControl("'" + addressType + "'").ClientID%>').value = val; ...

Activation of navigation buttons in the Vue Full Calendar control the movement to the next and previous

In my current project, I am utilizing https://www.npmjs.com/package/vue-full-calendar. However, I have encountered an issue when trying to receive callbacks or triggers from the next and previous buttons on the calendar. My backend API is structured aroun ...

Adjust the size of the embedded iframe to match the dimensions of the containing div

Is there a method to resize the iframe embed code for a vine so that it fits within the boundaries of the enclosing div? The supplied embed code already includes sizing information as shown below: <iframe src="https://vine.co/v/iMJzrThFhDL/embed/simp ...