[英]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代码任务:是使用 JWT 令牌从数据库中删除文档错误:发送 500 内部错误
code of Auth.js 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)删除文档的代码(API 端点)
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 .问题是即使我发送了不正确的 JWT 令牌,它也应该给我
{error : please authenticate}
但我也没有收到此错误,而是在发送正确的 JWT 时收到 500 内部错误和相同的错误。 Even I am printing error in console ,its not showing error in console即使我在控制台中打印错误,它也没有在控制台中显示错误
In your API endpoint, you have to call your collection name then you need to remove with query/params id.在您的 API 端点中,您必须调用您的集合名称,然后您需要使用查询/参数 ID 删除。
If you are using mongoose Like this and send id from frontend as query/params,如果您像这样使用 mongoose 并从前端发送 id 作为查询/参数,
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();
这是删除
await req.user.remove();
Because, when code executes it will don't know which collection of data needs to remove.因为,当代码执行时,它不知道需要删除哪个数据集合。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.