Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete mongodb document by id in express js

I'm pulling my hair for this...trying to delete document by id:

router.delete('/api/menu/delete/:id', function (req, res) {
  var id = req.params.id;
  db.get().collection('menu', function (err, col) {
   col.deleteOne({_id: new mongodb.ObjectID(id)});
  });
  res.json({ success: id })
});

Always getting :

Cannot read property deleteOne of undefined

When trying to find records it's working as expected.

like image 611
eladr Avatar asked Jan 03 '23 23:01

eladr


1 Answers

Got it. First thing i require the mongodb

mongo = require('mongodb')

And then :

router.delete('/api/menu/delete/:id', function (req, res) {
  var id = req.params.id;
  var collection = db.get().collection('menu');

  collection.deleteOne({ _id: new mongo.ObjectId(id) }, function (err, results) {
  });

  res.json({ success: id })
});
like image 185
eladr Avatar answered Jan 05 '23 15:01

eladr