0

I am new to node and mongo db. I have a list of users with delete link in each row.I am trying to delete a user with its _id. However its not working. Here is my router code.

router.get('/delete/:id', function (req,res) {
    const ObjectId = require('mongodb').ObjectID;
    var id = req.params.id;
    console.log(id);
    db.collection('users').deleteOne({ _id: ObjectId(req.params.id) }, function(err, res) {
        if (err) {
        throw err;
        } else {
          return res.redirect('/'); 
        }
      });

  });

Here is my view, on clicking this link I am getting the _id in my url as this : http://localhost:3000/delete/4428439e14e3343ba4ac31c1

<td><a href="/delete/ <%=  userdetails._id %>">Delete</a></td> 

console.log(id) gives me 4428439e14e3343ba4ac31c1

But it throws me the below error

Error: Argument passed in must be a single String of 12 bytes or a string of 24 hex characters at new ObjectID

Oops
  • 1,373
  • 3
  • 16
  • 46

4 Answers4

1

You need to create a instance of ObjectId using new. Currently, you are passing the ObjectId directly so you are getting that error.

db.collection('users').deleteOne({_id: new ObjectId(req.params.id)},  function(err, res) {
  if (err) {
    throw err;
  } else {
    return res.redirect('/');
  }
});
Ankit Agarwal
  • 30,378
  • 5
  • 37
  • 62
1

Try this, you don't need to create ObjectID if the string is a valid ObjectID

For prevention, you can use a function like below to test if valid ObjectID is passed or not

function validateObjectId (id) {
    if (ObjectId.isValid(id)) {
        const obj = new ObjectId(id);
        if (obj == id) {
            return true;
        }
    }
    return false;
},


if(!validateObjectId(req.params.id))
    return res.send({'error':'Invalid ObjectID Passed',id:req.params.id});

db.collection('users').deleteOne({ _id: ObjectId(req.params.id) }, function(err, res) 
{
    if (err) {
    throw err;
    } else {
      return res.redirect('/'); 
    }
  });

Also remove extra space from here

<td><a href="/delete/<%=userdetails._id%>">Delete</a></td> 
Sarfraaz
  • 1,273
  • 4
  • 15
1

Maybe you can try this code below:

router.get("/delete/:id", function(req, res) {
  const ObjectId = require("mongodb").ObjectId;
  var { id } = req.params;
  console.log(id);
  db.collection("users").findOneAndDelete({ _id: ObjectId(id) }, function(
    error,
    response
  ) {
    if (error) {
      throw err;
    } else {
      return res.redirect("/");
    }
  });
});

Updated:

Try looking at your code. There's confusing code, you use 2 times res. One is res from express and the other isres when it succeeds in removing at mongodb.

So, the res.redirect ('/') that you use in your mongodb function is res from mongodb, notres from express.

Try replacing {err, res} with {error, response}.

I hope it can help you.

Titus Sutio Fanpula
  • 3,467
  • 4
  • 14
  • 33
  • 1
    Same error : Argument passed in must be a single String of 12 bytes or a string of 24 hex characters – Oops Jan 27 '20 at 07:57
  • I've been try that code above and it's working fine. Have you copied my code and tried it? – Titus Sutio Fanpula Jan 27 '20 at 07:58
  • I've been try at my self and how to fix it is try to comment out your code that you think is wrong, after that save and reload your page. If you don't get an error, please open the comment and everything will return to normal. That's what I just did. – Titus Sutio Fanpula Jan 27 '20 at 08:14
  • Thank you for the code.Issue was with the extra space in my href link. – Oops Jan 27 '20 at 08:54
1

you can use findByIdAndRemove

router.get('/delete/:id', function (req,res) {
    var id  = req.params.id;
    db.collection('users').findByIdAndRemove( id , function(err, res) {
        if (err) {
        throw err;
        } else {
          return res.redirect('/'); 
        }
      });

  });
Prakash Karena
  • 2,525
  • 1
  • 7
  • 16