0

Using mongodb and monk. I'm trying to delete a record and I keep on getting the error: Error: Argument passed in must be a single String of 12 bytes or a string of 24 hex characters in hex format Different code that I have tried:

 router.get('/delete/:id', function(req, res) { 
    var db = req.db;
    var uid = req.params.id.toString();
    var collection = db.get('usercollection');
    collection.remove({"_id":uid}, function(err, result) { 
        if(result === 0){
            res.send("There was a problem delete the information to the database.");
        }
        else{
            res.location("list");
            res.send(res.redirect("list"));
        }
    });
    });
    module.exports = router;

Here is jade file

   List
ul
    each event, i in list
        li
            #{event.id} : #{event.text}
            a(href="/delete/#{event._id}") Delete
Daniil Yasnov
  • 31
  • 1
  • 9

2 Answers2

0

Since you are getting the id as string, you have to convert the string to mongodb object using ObjectID(uid) because "_id" accept mongo object only. You can use try this

router.get('/delete/:id', function(req, res) { 
    var db = req.db;
    var uid = req.params.id.toString();
    var collection = db.get('usercollection');
    collection.remove({"_id":ObjectID(uid)}, function(err, result) { 
        if(result === 0){
            res.send("There was a problem delete the information to the database.");
        }
        else{
            res.location("list");
            res.send(res.redirect("list"));
        }
    });
    });
    module.exports = router;
Mukesh Agarwal
  • 530
  • 4
  • 15
-1

link from Argument passed in must be a string of 24 hex characters - I think it is

In my case, this worked:

var myId = JSON.parse(req.body.id);
    collection.findOne({'_id': ObjectID(myId)}, function(error,doc) {
    if (error) {
      callback(error);
    } else {
       callback(null, doc);
    }
});
Yar Zar
  • 1
  • 1
  • Please do not copy existing answers. If you think that the question is already answered elsewhere, you will be able to comment or flag as a duplicate once you gain more reputation. – Adam Michalik Mar 29 '18 at 09:55