O'Reilly logo

JavaScript JSON Cookbook by Ray Rischpater

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Using REST to delete a document in MongoDB

Like updating, deletion takes an object id, which we pass in the URL to the HTTP DELETE request.

How to do it...

The doRemove method gets the object id from the id field in the form, and posts a DELETE message to the server at a URL consisting of the base URL plus the object id:

function doRemove()
{
  var id = $('#id').val();

  if(id == "")'') 
  {
    alert("Must provide an ID to delete!");
    return;
  }

  $.ajax({
    type: 'DELETE',
    url: "http://localhost:3000/documents/" + id  })
  .done(function(result) {
    $('#json').html(JSON.stringify(result));
    var resultHtml = "Deleted";
    $('#result').html(resultHtml);
  });
  }

The deletion message handler on the server extracts the ID from the URL and then performs a remove operation:

exports.deleteDocuments ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required