FindOneAndUpdate() and .exec() are depracated in the latest versions of mongoose so you will need to check which versions you're running.
Current version replaces FindOneAndUpdate() with updateOne()
And exec() is not needed to execute anymore.
Also instead of having 2 responses
res.status(403); res.json({ message: "invalid credentials" });
You can return both in just one response
res.status(403).json({ message: "invalid credentials" });
This should work just fine assuming that post_id and comm_id are valid
I put in a try{}catch so maybe it will return a useful error message if there is still an issue
Depractated version
app.delete("/comment", async function (req, res) {
const { authorization } = req.headers;
const [token] = authorization.split(" ");
const [username, password] = token.split(":");
const {post_id, comm_id} = req.body.postItems;
const user = await User.findOne({ username }).exec();
if (!user || user.password !== password) {
res.status(403).json({ message: "invalid credentials" });
return ;
}
try{
const post = await Post.FindOneAndUpdate(
{ _id: post_id },
{ $pull: { 'comments': { _id: comm_id } } }
);
res.status(200).json(post, + "Comment Deleted!")
}catch(err){
res.status(400).json({messsage: err})
}
});
Current version
app.delete("/comment", async function (req, res) {
const { authorization } = req.headers;
const [token] = authorization.split(" ");
const [username, password] = token.split(":");
const {post_id, comm_id} = req.body.postItems;
const user = await User.findOne({ username });
if (!user || user.password !== password) {
res.status(403).json({ message: "invalid credentials" });
return ;
}
try{
const post = await Post.updateOne(
{ _id: post_id },
{ $pull: { comments: { _id: comm_id } } }
);
res.status(200).json(post, + "Comment Deleted!")
}catch(err){
res.status(400).json({messsage: err})
}
});
I'm unsure on the exact anwser to your issue but hopefully this is of some use to you
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…