MongoDb delete documents by passing user id

2.9k Views Asked by At

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

4

There are 4 best solutions below

3
Sarfraaz On BEST ANSWER

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> 
3
Ankit Agarwal On

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('/');
  }
});
4
Titus Sutio Fanpula On

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.

4
Prakash Karena On

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('/'); 
        }
      });

  });