MongoDB: Issue updating the 'role' field of a document

Recently, I've run into an issue where I am unable to update the 'role' of a specific document. The document in question is a 'user' object within the MEANjs User schema, and it has a pre-defined property for roles. Here is the section of the schema concerning roles:

roles: {
        type: [{
            type: String,
            enum: ['user','volunteer','participant','manager', 'admin']
        }],
        default: ['volunteer']
    }

When attempting to update this field using a regular PUT request, the response comes back as OK (200) but no changes are reflected in the data. Surprisingly, when using the same method to update a custom field that I have created, it works perfectly fine.

Could this be related to the enum defined in the schema? Any ideas or suggestions would be greatly appreciated!

Thank you in advance!

PS - Just to note, the document's version (__v) is not causing any issues in this scenario.

Answer №1

It is the standard behavior to delete roles as a security precaution when updating a user profile. This measure prevents users from assigning themselves unauthorized privileges, such as admin access.

/**
 * Update user details
 */
exports.update = function (req, res) {
  // Initialize Variables
  var user = req.user;

  // To ensure security, roles are removed from the req.body object
  delete req.body.roles;

  ...

In the most recent version of MEAN.js, administrators have the ability to change user roles by referring to the

modules/users/server/controllers/admin.server.controller.js
file:

/**
 * Update a User
 */
exports.update = function (req, res) {
  var user = req.model;

  // Merge only these parameters for security reasons
  user.firstName = req.body.firstName;
  user.lastName = req.body.lastName;
  user.displayName = user.firstName + ' ' + user.lastName;
  user.roles = req.body.roles;

  user.save(function (err) {
    if (err) {
      return res.status(400).send({
        message: errorHandler.getErrorMessage(err)
      });
    }

    res.json(user);
  });
};

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

Activate function when list item is clicked

My goal is to execute a function when users click on the li elements in the snippet below without relying solely on onclick. For instance, clicking on the first li element (with a value of 1) should trigger a function where the value "1" is passed as an ar ...

Ways to update a nested object by utilizing the setState method

I have a situation where I need to modify the key/value pairs of an object in my state. Specifically, I need to add a key/value pair to the object with an ID of 13. Please refer to the attached photo for reference. Although I know how to use setState, I ...

Techniques for incorporating a variable into the value field in JavaScript

let y = data[1]; cell1.innerHTML ='<input id="text" type="text" value= "'y'"/>' ; This snippet of code does not render any content when attempting to pass the variable, but if you provide a specific value like "h", it will displa ...

Doing nested ng-repeats in Angular

I am currently working on a project that involves combining two ng-repeats. Does anyone know how to achieve this? Here is an example of what I'm trying to do: <th ng-repeat="header in headers"> ...

Baffled by the data visualization produced by Google Chart using information from

Perhaps I'm being a bit ambitious, but I managed to create a basic Chart using GoogleCharts. The problem is that I have to input the values manually, but I want to retrieve them from the Database. I know JSON can accomplish this, but I've spent f ...

Navigating within a React application - rendering JSX components based on URL parameters

As I work on developing a web-app with a chapter/lesson structure, I have been exploring ways to handle the organization of lessons without storing HTML or React code in my database. One idea I had was to save each lesson as a .jsx file within a folder str ...

Unable to display an image element in fullscreen within a modal that is already fullscreen

I am facing an issue with my modal that is designed to occupy the full width and height of a browser. Inside this modal, there is an image enclosed within a div along with some other elements. My goal is to make the image go full screen in the browser, aki ...

Loading content dynamically into a div from an external or internal source can greatly enhance user experience on a website. By

As I work on my website, I am incorporating a div structure as shown below: <div class="container"> <div class="one-third column"> <a id="tab1" href="inc/tab1.html"><h2>tab1</h2></a> </div> & ...

Tips on testing third party library functions in Angular unit testing

Currently, I'm in the process of testing Angular services using Karma and Jasmine. Within my services, I've implemented sprintf() from the sprintf-js module to generate strings. However, when attempting to test the service, an error is occurring ...

Vue.js - Leveraging arrays in functions for efficient iteration

I need help using a JS array in a Vue.js function for looping. Here is the code I tried: Vue: computed: { bbb: function(){ var vvv=this.Preused.length-this.quote.lines.length; let added_products=[]; if(vvv > 0){ for(var i = 0; i <= vvv-1 ...

Retrieving data from an array using an AJAX request function

I've been attempting to utilize an AJAX call to update a series of image elements on a webpage. The array containing the elements to update is populated with URLs fetched from a PHP page via AJAX. The issue I'm encountering with the code provide ...

Switch between different templates by toggling their individual URLs in Angular

Currently, I am trying to implement a way to switch between different views on a single page using Angular. Although I have already set it up with routes, I believe there may be a better practice for my application. I am looking for guidance on how to tog ...

Protractor synchronization with the page exceeded the time limit of 50001ms and timed out

I am currently testing an AngularJS application and I am relatively new to using protractor. Whenever I open the browser, it opens successfully but then waits for a timeout before displaying the following error in the command prompt. Protractor synchron ...

Attempting to incorporate a factory within a restricted function

Just starting out with AngularJS and I have a question. Can I use a factory code (logger) inside a private function like the example below? I'm still working on understanding angular concepts. Thanks for your help: (function () { 'use strict ...

Updating the head() properties in Nuxt.js via asyncData() is not possible

After creating a server-side rendered Vue.js blog with Nuxt.js using Typescript and Ghost, I encountered a problem updating html metatags with data from asyncData(). According to the Nuxt.js documentation, asyncData() is triggered before loading page comp ...

Firefox compatibility issue caused by jQuery's appendTo function disrupting hyperlink functionality

I've successfully implemented the material design ripple effect using jQuery, which functions well in IE11 and Chrome 46. However, I've encountered an issue in Firefox 39 where applying the effect to links prevents redirection. Upon investigation ...

What is the proper way to import Axios in Vue 3 once you have created a new project using the CLI?

When starting a new project, I used the command: vue create hello-world This generated essential files like HelloWorld.vue, app.vue, and main.js. Next, I followed the documentation on Npm vue-axios to install Axios: npm install --save axios vue-axios In ...

How can I set individual items in a JSON object to different scope variables in AngularJS?

My JSON object is as follows: const data = {item1: "Hello1", item2: "Hello2", item3: "Hello3", item4: "Hello4", item5: "Hello5"}; I am looking to make each item available in the scope like this: $scope.item1 $scope.item2 ... Can this be done in Angular ...

When the mouse leaves, the gauge chart component's size will expand

I have encountered a problem while using the react-gauge-chart library in my react project. Within the project, I have integrated a popover component using material-ui and incorporated the gauge chart component from the library within the popover modal. T ...

Conversion of UTC timestamp to a timestamp in the specified timezone

this.selectedTimezone="Pacific/Kiritimati"; //this value will come from a dropdown menu These records represent the data.body returned by an API call. Iterating through each record in the dataset: { We are creating a new Date object based on the ...