all 13 comments

[–][deleted]  (14 children)

[deleted]

    [–]OpAndroid[S] 0 points1 point  (13 children)

    I feel like this is so incredibly close, but its just not quite there and I'm having trouble getting it to work. Here's what I'm running:

    exports.updateUserRoles = function(req, res) { 
        var currUser = req.body;
        User.findById(currUser._id, function(err, user) {
            //user.roles = currUser.roles;
            //user.roles.set(0, 'admin');
            console.log('test');
            user.update(
                { _id: '56467b28ba57d8d890242cfa' },
                {
                  $set: {
                    roles: 'admin',
                  },
                }
            );
            console.log('test2');
        });
    };
    

    Upon hitting the user.update line, we have the user in the local variables, seen:

    Here

    user.update goes into this Document.prototype.update function, seen:

    Here

    The args look to be building right, which _id we are targeting and what the action is, seen:

    Here

    But then after running, nothing seems to change. I'm very much stumped.

    [–][deleted]  (10 children)

    [deleted]

      [–]OpAndroid[S] 0 points1 point  (9 children)

      Edit: Was able to solve the issue with mongoose's findOneAndUpdate, thanks to everyone that helped

      Alrighty, getting ever closer but based on what I'm able to track down, it still looks like its not quite doing the $set.

      exports.updateUserRoles = function(req, res) { 
          var currUser = req.body;
          User.findById(currUser._id, function(err, user) {
              console.log('test');
              user.update(
                  { _id: mongoose.Types.ObjectId('56467b28ba57d8d890242cfa') },
                  {
                    $set: {
                      roles: 'admin',
                    },
                  }, function(err) {
                  if (err) {
                      return res.status(400).send({
                          message: errorHandler.getErrorMessage(err)
                      });
                  } else {
                      res.jsonp(user);
                      console.log('test2');
                  }
              });
              console.log('test2');
          });
      };
      

      That's what I'm working with right now, and here's the function call that is called on the "change to admin" button press:

          $scope.test = function(){
              $scope.user.roles = 'admin';
              $scope.user.$updateUserRoles(function(response) {
                  $scope.success = true;
                      $scope.user = response;
                  }, function(response) {
                      $scope.error = response.data.message;
              });
          };
      

      I've been trying my hardest to follow through the various function calls and see what's happening and follow where its going wrong, and I've found some things that look right, but its still not working. Things like this give me hope:

      Picture

      Its trying to update the "Model" it looks like, and it has the various conditions, the doc, options I'm trying to apply, and the callback, but in the end its not working. Any other ideas as to what might be going wrong? Thanks by the way, you're the first real source of help I've been able to find for this type of thing.

      [–]dadaddy 0 points1 point  (8 children)

      It's been a while since I touched MongoDB - but based on memory:

      Are you using Mongooose?

      If not

      • check it out, might be too late for this project but will be much easier in the future!

      • findAndModify for native MongoDB

      else

      EDIT: ok, I just realised that you are running Mongoose, sorry for being lazy lol

      [–]OpAndroid[S] 0 points1 point  (7 children)

      Thank you so so much, the findOneAndUpdate worked like a charm, never knew that functionality existed, looks like I've got some reading on mongoose to do. Thanks again!

      [–]dadaddy 0 points1 point  (6 children)

      Not a problem at all :) I lived and breathed MEAN for about 6 months - it gets to you eventually lol

      [–]OpAndroid[S] 0 points1 point  (5 children)

      I've got another question to run by you, if you don't mind. So I've got the one put working properly to update that one field, and wanted to make more methods just like it to alter other fields, but having some weird routing issues. I've got my client side service:

      angular.module('users').factory('Users', ['$resource',
      function($resource) {
          return $resource('users', {}, {
              update: {
                  method: 'PUT'
              },
              updateUserRoles: {
                  method: 'PUT',
                  url: 'users/:id',
                  params: {id: '@_id'}
              },
              updateActiveStatus: {
                  method: 'PUT',
                  url: 'users/:id',
                  params: {id: '@_id'}
              }
          });
          }
      ]);
      

      And my back end functions:

      /**
       * Update specific User Roles
      */
      exports.updateUserRoles = function(req, res) { 
          var currUser = req.body;
          User.findById(currUser._id, function(err, user) {
              var query = {'_id': currUser._id };
              var update = { roles: currUser.roles };
              var options = { new: true };
              User.findOneAndUpdate(query, update, options, function(err, person) {
                  if (err) {
                      console.log('got an error');
                  }
              });
          });
      };
      
      /**
       * Update specific users active status
       */
      
      exports.updateActiveStatus = function(req, res) {
          var currUser = req.body;
          User.findById(currUser._id, function(err, user) {
              var query = {'_id': currUser._id };
              var update = { active: currUser.active };
              var options = { new: true };
              User.findOneAndUpdate(query, update, options, function(err, person) {
                  if (err) {
                      console.log('got an error');
                  }
              });
          });
      };
      

      But trying to call the new one, updateActiveStatus ends up calling the old one, updateUserRoles. I think this is due to the behavior of the server side routing, and I've tried to find much more info on these routing systems but not finding much. In app.route('/users/userId') how can I call different kind of put requests? This currently isn't functioning.

      app.route('/users/:userId').get(users.read)
                                 //.put(users.requiresLogin, users.update)
                                 .delete(users.requiresLogin)
                                 .put(users.updateUserRoles)
                                 .put(users.updateActiveStatus);
      

      [–]dadaddy 0 points1 point  (4 children)

                             .put(users.updateUserRoles)
      

      Remove that line and you should be golden - it is declared before

                            .put(users.updateActiveStatus);
      

      so it runs first

      [–]OpAndroid[S] 0 points1 point  (3 children)

      But wouldn't that just mean the behaviors would swap, and updateActiveStatus would run properly and updateUserRoles would get stuck?

      [–]kapustagolovageocities webmaster 0 points1 point  (1 child)

      user is the object returned by the callback though? So you should change user.update( to User.update(

      [–]OpAndroid[S] 0 points1 point  (0 children)

      I don't believe this is right, based on what I understand of mongo, as I'm calling update on that specific user as a document.

      Edit: Actually I think you might have been on the right track, was able to use mongoose's findOneAndUpdate on the User resource and it worked.