Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

183
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda