I am currently working on a delete function on the backend so that only authorized users can delete their reviews if they want to. I am currently trying to test it through POSTMAN but I am getting the error "Argument passed in must be a single String of 12 bytes or a string of 24 hex characters".
Currently, my POSTMAN is set up where the user is already logged in and I used their auth token and set it as the authorization header for the delete function
router.delete("/delete/:reviewId", requireAuth, async (req, res, next) => {
const { user } = req
const { reviewId } = req.params
const review = await Review.findById(reviewId)
console.log(reviewId)
console.log(review)
if (!review) {
return response.status(422).json({ error: "Cannot find review" })
}
console.log(review.author._id.toString(), typeof review.author._id.toString())
console.log(user.id, typeof user.id)
if (review.author._id.toString() === user.id) {
console.log("if is working")
try {
const removedReview = await review.remove()
console.log("deleted review")
const userUpdate = await User.updateOne(
{ _id: user.id },
{ $pull: { reviews: reviewId } }
)
res.json(removedReview)
} catch (err) {
next(err)
}
}
})
I currently don't have enough rep to embed the image into the post.
This issue is surely related with _id that is sent to the mongoDB. You should check the validity of all _ds you used in this code block. The _d must be type of ObjectID to be precise. You can use typeof operator to determine its type. If it is other than ObjectID simply convert it.
var ObjectId = require('mongodb').ObjectID;
Model.findById(new ObjectId(yourId))
Let me know if it helped:)