Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

180
Views
document not getting deleted in mongo using jwt token

Task of code : Is to delete document from DB using JWT token error : sending 500 internal error

code of Auth.js

const auth=async(req,res,next)=>{
try{
    const token=req.header('Authorization').replace('Bearer ','');
    const decoded=jwt.verify(token,'helloworld');
    const user=await User.findOne({_id:decoded._id,'tokens.token':token});
    if(!user){
        throw new Error();
    }
    // console.log(token);
    req.token=token;
    req.user=user;
    next();
}
catch(err){
    // console.log(token);
    res.status(401).send({error:"please authenticate"});
}
}
module.exports=auth;

Code To delete document (API endpoint)

router.delete('/users/me',auth,async(req,res)=>{
try{
    await req.user.remove();
    res.status(201).send(req.user);
}
catch(err){
    console.log(err);
    console.log(req.user);
    res.status(500).send();
}

})

The Problem is even if I am sending incorrect JWT token it should give me {error : please authenticate} but I am not getting this error too instead I am getting 500 internal error and same error when sending correct JWT . Even I am printing error in console ,its not showing error in console

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

In your API endpoint, you have to call your collection name then you need to remove with query/params id.

If you are using mongoose Like this and send id from frontend as query/params,

Model.remove({ _id: req.body.id }, function(err) {
  if (!err) {
    message.type = 'notification!';
  } else {
    message.type = 'error';
  }
});

or

router.delete('/users/me/:id', auth, async(req,res) => {
  try {
    await Model.deleteOne({ _id: req.params.id})
    res.status(201).send(req.user);
  } catch(err) {
    console.log(err);
    res.status(500).send();
  }
});

I hope if you follow this way you can solve this problem.

This is the wrong way to remove await req.user.remove(); Because, when code executes it will don't know which collection of data needs to remove.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!