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 = function(req, res) {
var id = new objectId(req.params.id);
db.collection('documents', function(err, collection) {
collection.remove({'_id':id}, {safe:true},
function(err...