When I use the Put method in Express, I receive a 200 status code, but no changes

Hello everyone, I recently attempted to implement my update function and tested it using Postman. I wanted to update the firstName field, but despite receiving a "HTTP/1.1" 200 response in the console, nothing was actually updated.

This is the response body displayed in Postman:

{
    "user_id": "5adaa55c0364d01cd9478492",
    "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiI1YWRhYTU1YzAzNjRkMDFjZDk0Nzg0OTIiLCJpYX4OTJ9.JpDShf4iBFBCQ5rGflKbsj3jisl-PS68UOTnVpxNyXs",
    "data": {
        "userData": [
            {
                "address": [
                    {}
                ]
            }
        ]
    }
}

This is the content that I attempted to update:

{
    "data": {
        "userData": [
            {
                "firstName": "George"
            }
        ]
    }
}

Below is the code snippet for my update function located in authentication_controller.js:

exports.update = function (req, res, next) {
  var email = req.body.email;
  var password = req.body.password;
  var role = req.body.role;
  var firstName = req.body.firstName;
  var lastName = req.body.lastName;
  var phone = req.body.phone;
  var number = req.body.number;
  var street = req.body.street;
  var city = req.body.city;
  var postcode = req.body.postcode;
  var user = req.user;

  user.save(function (err) {
    if (err) {
      return next(err)
    } else {
      res.json({
        user_id: user._id,
        token: tokenForUser(user),
        data: {
          email: email,
          password: password,
          userData: [{
            role: role,
            firstName: firstName,
            lastName: lastName,
            phone: phone,
            address: [{
              number: number,
              street: street,
              city: city,
              postcode: postcode
            }],
          }],
        }
      });
    }
  });
}

Furthermore, here is the excerpt from my route.js file:

router.route('/users/:user_id/data')
  .get(requireAuth, AuthenticationController.index)
  .put(requireAuth, AuthenticationController.update);

Answer №1

Make sure you are not forgetting to call your mongoose model when updating user information. Instead of just accessing the user object from req, which is set by the requireAuth middleware when decoding the JWT, use your actual mongoose User model:

const User = require('./path/to/mongoose/model/User')

...

// assuming the decoded JWT user object has an `id` property
User.findByIdAndUpdate(req.user.id, req.body)
    .exec()
    .then(doc => res.json(doc)
    .catch(err => res.json(err))

http://mongoosejs.com/docs/api.html#findbyidandupdate_findByIdAndUpdate

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

Angular: Enhance communication with controllers and directives

Currently, I am in the process of learning Angular. One interesting feature I have been working on is a directive that displays a select element. Whenever there is a change in this select element due to the ng-change event, a specific method defined in the ...

How can I remove a row from a JavaScript array based on the value of the first item in the row?

Creating an array in JavaScript can be done like this: var myArray = new Array(); myArray.push({ url: urlValue, filename: fileNameValue }); As time goes on, the array will accumulate various items. If you need to delete a specific row based on the urlVal ...

Mastering the ins and outs of ngStorage in AngularJS

Imagine a web page featuring a form that allows users to input multiple entries before submitting. As each entry is added, a summary of the data entered is displayed in a table at the top. Once all entries are completed, the user can then proceed to submit ...

How can JQuery be utilized to extract the information stored in the "value" parameter of a chosen option?

I have a dropdown menu that dynamically populates its options with numbers. Here is the code for that: <select name="TheServices" id="services-selector"> <option value="" disabled selected hidden>Static Select ...

Words program with the header feature incorporated

Hello, I am currently working with Laravel to build an HTML page and have successfully converted it to MS Word. However, I am now trying to add a header inside. Can anyone help me achieve this? Here is a snippet of my code: <body> <a class= ...

Concealing Bootstrap Dialog in Angular 6 through Component隐藏Angular 6中

I have been struggling to hide a bootstrap dialog from a component with no success. Here is my Dialog code: <div class="modal fade" id="loading_video_upload" tabindex="-1" role="dialog" aria-labelledby="loading_video_upload_label" aria-hidde ...

json-server does not rely on the code found within the middleware file

While working on front-end development, I decided to use json-server to mimic some API calls. However, I encountered an issue with adding a middleware: { "name": "my-app", "version": "0.1.0", "private": true, "scripts": { "serve": "concurrentl ...

Creating Vue3 Component Instances Dynamically with a Button Click

Working with Vue2 was a breeze: <template> <button :class="type"><slot /></button> </template> <script> export default { name: 'Button', props: [ 'type' ], } </scr ...

The node.js and express.js update operation (CRUD) is not rendering the CSS files properly

I am currently developing a CRUD app using Node.js/Express.js with EJS as the templating engine. The concept I'm working on involves displaying user_ids from a database, and when an admin clicks on a user_id, it should redirect them to the edit_team. ...

Using jQuery and AJAX manipulates the value of my variable

My AJAX request seems to be causing jQuery to change the variable that is passed to it. Here is the JavaScript code: <script type="text/javascript"> function ResolveName(id) { $.ajax({ url : 'resolvename.php', ...

Always keep your phone in landscape orientation for optimal website viewing

Currently, I am facing an issue with my website where it functions perfectly on mobile devices in landscape orientation but elements get distorted when viewed in portrait mode. Is there a method to ensure that the website is always displayed in landscape ...

How can parameters be included in ng-href when using ng-click?

So I have this list of products and I want to pass the current product id when clicking on ng-href by using a function with ng-click in the ng-href. This is what my html file looks like: <div class="agile_top_brands_grids" ng-model="products" ng-repe ...

Applying CSS styles to a class dynamically using JavaScript

Is there a way to dynamically add a new CSS property to an existing class using JavaScript? Let's say I have a class called .test with some pre-defined styling. How can I append the property color: blue; to this class using JavaScript? const elm ...

Enhance the textarea using Javascript when clicked

I am experimenting with styling my textarea using a combination of JAVASCRIPT and CSS. The goal is to make it expand in size from 20px height to 120px height when clicked, using document.getElementById("tweet_area"). However, I am facing an issue where t ...

What are some ways to streamline this D3 script?

My CSV data displays pass rates by organisation for different years: org,org_cat,2004_passed,2004_total,2005_passed,2005_total,2006_passed,2006_total GSK,industry,35,100,45,100,55,100 I am using D3 and aiming to create a dictionary of organisations struc ...

Is there a way to ensure that a "catch all other" route in the Vue Router will also capture the URL if a portion of it matches a predefined route?

After following the suggestion to implement a catch all route from this article, I realized that it does not capture URLs that partially match a defined route. routes: [ { path: "/album/:album", name: "album", component: Album, } ...

Dealing with information obtained through ajax requests

Trying to send data from modal using ajax. Below is the code snippet I am using, however, it seems that the first IF block is causing issues. If I comment it out, I can access the $_POST['id'] variable, but otherwise, it doesn't work. ...

What are some solutions for resolving an infinite loop of axios requests?

I am currently in the process of developing a web app for Spotify using its API. I have encountered an issue where the handleClick function in Albums.js is being called repeatedly when trying to make a get request for specific artist album data. Could this ...

Setting up event listeners from a string array (using PIXI.js)

Hey there! I've encountered a bit of an interesting challenge that could easily be resolved by duplicating the code, but where's the fun in that? This project is more of an experiment for me, just to prove that I can do it. However, the idea has ...

What is the method for writing to an HTML file with the use of expressjs?

Alright, I have an interesting idea here. I am looking for a way to allow users to push a button and have a new p element permanently added to the HTML file. This means that even after reloading the page, everyone should be able to see this new element. An ...