I am trying to delete records based on ID. I am sending the ID via the get verb and acessing it from req.params.id. My code isn't working. What am I doing wrong?
//delete user
router.get('/deleteuser/:id', function(req, res){
var db = req.db;
db.users.remove({'_id':req.params.id}, function(err, docs) {
if (err) return err;
res.send(docs); // see results
});
});
I realize I need to add "ObjectId" before req.params.id. However, concatenating is not working. I have this so far. Is there another way:
//delete user
router.get('/deleteuser/:id', function(req, res){
var db = req.db;
var objId = 'ObjectId("' + req.params.id + '")';
console.log(objId);
db.users.remove({"_id": objId}, function(err, docs) {
//db.users.remove({"_id": ObjectId("4d512b45cc9374271b02ec4f")}); works in mongo console
if (err) return err;
console.log(docs);
res.send(docs);
});
});
This worked:
// db.ObjectId(req.params.id)
router.get('/deleteuser/:id', function(req, res){
var db = req.db;
db.users.remove({"_id": db.ObjectId(req.params.id)}, function(err, docs) { //db.users.remove({"_id": ObjectId("4d512b45cc9374271b02ec4f")});
if (err) return err;
console.log(docs);
res.send(docs);
});
});
_id
? If it is anObjectId
, then you need to give it anObjectID
object, which you can build from the base64 representation with the constructor:new ObjectID(req.params.id)
– JemieGET
to delete an entity, which seems very evil, how do you know it isn't working? What happens? Do you get an error? Is the document still in the database after you delete it? What is the output ofdocs
? – JemieGET
for a moment, have you considered the effects of caching? Are you sure your requests are hitting your server? A print statement may help with this. – Jemie