MongoDB | Can not update 'role' of document

我是研究僧i 提交于 2020-01-06 20:08:09

问题


So I have this problem where I can not update a 'role' of document. The document is a 'user' (the User schema in MEANjs) object and it got its pre-defined roles property. This is the roles part from the schema :

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

And I'm updating it via regular PUT request. The request returns OK (200) but nothing changes. If I'm using the same method to update another field (a custom one that i've created) it works fine.

Any clue ? maybe something with the enum here ?

thanks !

PS - document's version ( __v ) is off so nothing to do with this


回答1:


That is indeed the expected behaviour since the roles are deleted by default as a security measure if you try to update the profile as a user, otherwise any user could just add roles to himself and get for example admin privileges. The file where they are being deleted is /modules/users/server/controllers/users/users.profile.server.controller.js (in latest MEAN.js version):

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

  // For security measurement we remove the roles from the req.body object
  delete req.body.roles;

  ...

In the latest MEAN.js version you can change any user role if you have admin privileges (check file the modules/users/server/controllers/admin.server.controller.js):

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

  //For security purposes only merge these parameters
  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);
  });
};


来源:https://stackoverflow.com/questions/33037901/mongodb-can-not-update-role-of-document

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!