Kasparas
Kasparas

Reputation: 89

Mongoose does not remove a document from the database

Have a small/big problem.

I am trying to remove a document from a Mongoose database, but instead nothing happens.

Maybe someone has any suggestions?

This is my code from the NodeJS application:

router.delete('/delete/:id',(req , res) =>{

  Message.remove({"content": req.params.id}), function(err, result){
    if (err) {
      console.log(err);
    }

    res.redirect('/getMessages');

  };

 }); 

And this is my Jquery code:

$(document).ready(function()
{
    $('.deleteUser').on('click', deleteUser);
}
);

function deleteUser()
{
    var confirmation = confirm('Are you sure want to delete this message?');

    if (confirmation) {
        $.ajax({
            type: 'DELETE',
            url: '/delete/'+$(this).data('id')

        }).done(function(response){

            window.location.replace('getMessages');
        });
        window.location.replace('getMessages');
    }
    else{
        return false;
    }


}

Upvotes: 0

Views: 501

Answers (2)

Saroj
Saroj

Reputation: 1571

I think you have misplaced the callback.

Message.remove({"content": req.params.id}), function(err, result){
   if (err) {
      console.log(err);
   }    
   res.redirect('/getMessages');    
};

Here the callback should be inside the parenthesis not outside.

I ran the following code with "id" as a parameter and my record was removed. Hope you'r :id contains the data that is in your content field not the Id.

 // Index.js
<button type="button" class="btn btn-primary" id="deleteMessage" value="585bc7a2d1387569d13c304a">Delete</button>

 //sample.js
(function(){
    $('#deleteMessage').on("click",function(){           
         $.ajax({
            type: 'DELETE',
            url: '/delete/'+$(this).val()

        }).done(function(response){
            console.log(response);            
        }).fail(function(error){
            console.log(error);
        });           
    });
})();

Here is the route for delete :

router.delete('/delete/:id',function(req,res,next){      
  Message.remove({_id: req.params.id}, function(err,response){        
    if (err) {
      console.log(err);
    }    
    res.send(response);
  });

});

Upvotes: 1

madalinivascu
madalinivascu

Reputation: 32354

Don't redirect the page on the server side return something to the ajax:

router.delete('/delete/:id',(req , res) =>{

  Message.remove({"content": req.params.id}), function(err, result){
    if (err) {
      console.log(err);
    }

    res.json({status:'ok'});
    //res.send(JSON.stringify({status:'ok'}));

  };

 }); 

Upvotes: 0

Related Questions