Harry Harry - 2 months ago 19
AngularJS Question

How to send a request from express to mongodb to delete multiple record from collections

Delete multiple record from mongodb collections using angular and express.

How I can send array of ids from express to mongodb.

Here is code for deleting single todo from mongodb in express

app.delete('/api/todos/:id', function(req,res){
Todos.remove({
_id: req.params.id
}, function(err, todos){
if(err)
res.send(err);
Todos.find(function(err, todos){
if(err)
res.send(err)
res.json(todos);
});
});
});


angular controller code



$scope.deleteTodo = function(id){
$http.delete('/api/todos/'+ id).then(function(response){
var data = response.data;
$scope.todos = data;
});
}



Answer Source

Easy approach is to re-use your route by just passing comma-separated list of IDs e.g. /api/todos/id1,id2,id3.

app.delete('/api/todos/:ids', function (req, res) {
    Todos.remove({
        // convert string of IDs to array of IDs
        _id: { $in: req.params.ids.split(',') }
    }, function (err) {
        if (err) return res.send(err);
        Todos.find({}, function (err, todos) {
            if (err) return res.send(err)
            res.json(todos);
        });
    });
});