On reflection, a DELETE
verb probably is not appropriate for a "list" of content and this would be better suited to a POST
or PUT
or even PATCH
. For all of the other verbs it's generally accepted that these will have a request body which is suitable for keeping data such as a "list".
Generally there is nothing wrong with POST
and whilst it's not "official" that DELETE
should not send a content body, you are probably better off sticking with standards, at least from the perspective of what would be most widely supported should your "front end" end up talking to a different "back end" service structure at some later stage.
Therefore if we POST
instead, then your angular method would be:
deleteData(ids) {
// presuming this.api points to /tasks at the correct point
return this.http.post( this.api, { ids });
}
On the express side you would want to have the body-parser middleware set up if you have not already:
const bodyParser = require('body-parser');
app.use(bodyParser.json());
And then in your actual route controller, simply return the array from req.body
with a specifically named route for the POST
request:
app.post('/tasks/delete', function(req,res) {
var myquery = { _id: { $in: req.body.ids } };
Model.deleteMany(myquery, function(err, result) {
if (err) throw err;
if (result) {
res.json(result)
}
});
});
Noting also that mongoose supports deleteMany()
directly on the model, so there is no need to use the collection
accessor to the underlying driver Collection
object. Also using the mongoose method ensures that if your list of ids
are actually meant to be ObjectId
values ( as they typically are for _id
) then they will "autocast" from the strings as which they were sent from the client. Actually whatever the schema type is for the field in any query, mongoose will take care of this when using it's own methods.
Using DELETE
really should be reserved for single parameter requests "within the url" such as:
app.delete('/tasks/:id', function(req,res) {
var myquery = { _id: req.params.id };
Model.deleteOne(myquery, function(err, result) {
if (err) throw err;
if (result) {
res.json(result)
}
});
});