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 ...
Get JavaScript JSON Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.