Search code examples
javascriptnode.jsexpressnode-mongodb-native

espressjs, node, mongo saving method


i have this function "saveUser", which gets value from textbox, and updates information of the user and then uses ajax to post the object to our updateuser service.

function saveUser(event){

    event.preventDefault();

    var errorCount = 0;
    $('#editUser input').each(function(index, val) {
      if($(this).val() === '') { errorCount++; }
      });

    if(errorCount === 0) {
       var existingUser = {
        'username': $('#editUser fieldset input#inputUserName').val(),
        'email': $('#editUser fieldset input#inputUserEmail').val(),
        'fullname': $('#editUser fieldset input#inputUserFullname').val(),
        'age': $('#editUser fieldset input#inputUserAge').val(),
        'location': $('#editUser fieldset input#inputUserLocation').val(),
        'gender': $('#editUser fieldset input#inputUserGender').val()
         }

         $.ajax({
            type: 'POST',
            data: existingUser,
            url: '/users/updateuser/' + data_id,
            dataType: 'JSON'
         }).done(function( response ) {


        if (response.msg === '') {
            $('#editUser fieldset input').val('');
            populateTable();
            disableSaveBtn();
        }
        else {

            alert('Error: ' + response.msg);
        }
    });
}
  else {
      alert('Please fill in all fields');
      return false;
      }
 };

and this is the code for updateuser service.

  router.put('/updateuser/:id',function(req, res){
     var id = req.params.id;
     var user = req.body;
     delete user._id;
     console.log('Updating user: ' + id);
     console.log(JSON.stringify(user));
     db.collection('userlist', function(err, result) {
        collection.update({'_id':new BSON.ObjectID(id)}, user, {safe:true}, function(err, result) {
           if (err) {
               console.log('Error updating user: ' + err);
               res.send({'error':'An error has occurred'});
           } else {
               console.log('' + result + ' document(s) updated');
               res.send(user);
                  }
       });      
   });
});

when i click into users account and i edited it, then saving it,

i get this on my console:

POST /users/updateuser/53aca86c005afcbc0faac5be 404 128ms - 1.08kb

all of my operations are good, except for this operation. the adding user is working good, the deletion of user is working also, the retrieving of user based on the id is good also, except with this saving operation.


Solution

  • You are making post request. But your router is handling PUT request

    Use instead

    router.post('/updateuser/:id',function(req, res){