Delete document with findOneAndRemove Mongoose

I get this error when trying to delete a document from the database:

Impossible GET / delete / 532fa5e56f885c7fec5223b1fds

How can I successfully delete a document?

app.js

//Delete app.del('/delete/:id', routes.delete_offer); 

routes / index.js

  //Delete exports.delete_offer = function (req,res){ Offer.findOneAndRemove({'_id' : req.params.id}, function (err,offer){ res.redirect('/newsfeed'); }); }; 

view / dashboard.jade

  - each offer in offers div.offer.row a(href="/offer/" + offer._id) div.columns div.sell_type p=offer.type div.small-8.columns.sell_info p.sell_price="$" + offer.fixedPrice() + " " p.sell_location="@ " + offer.location + " β€Ί" div.small-4.columns.sell_pic p=offer.user_id a.delete(href="/delete/" + offer._id)="Delete Offer" 
+6
source share
4 answers

The HTTP verb you are using is incorrect use app.delete("/delete/:id", routes.delete_offer);

I think this should work. Cause I don’t think that in the HTTP verb for express.js there is no del method, basically it is GET, POST, PUT, DELETE plus a few others.

+5
source

So, you have a route configured for the verb DELETE in the sense of RESTful. You don't seem to call it that or use it in a RESTful way.

Your application should really treat this as a REST request and return the status and content as an answer corresponding to what happened. You are being redirected to another URL right now. This is the wrong approach. But if you just don't understand REST, then do it this way, but change the route to GET .

What is it worth once you understand your use and testing, perhaps using curl or the like, as shown . Then perhaps consider .findByIdAndRemove() instead.

 Offer.findByIdAndRemove(req.params.id, function (err,offer){ if(err) { throw err; } // ... } 

And then actually checking the answer is what you expect before just sending or sending a valid or erroneous answer. This is what you should do.

+1
source

If you use mongoose. You can fix the file routes /index.js.

 //Delete exports.delete_offer = function (req,res){ Offer.findOneAndRemove({_id : new mongoose.mongo.ObjectID(req.params.id)}, function (err,offer){ res.redirect('/newsfeed'); }); }; 
+1
source

Note that if you use the Mongoose findByIdAndRemove function to retrieve and remove an object from Model .

 exports.delete_offer = function(req, res) { Offer.findByIdAndRemove(req.params.id, function(err) { if (err) res.send(err); else res.json({ message: 'Offer Deleted!'}); }); } 
+1
source

All Articles