I can't delete a specific document by its id
in MongoDB.
In Next.js, I have this handler to delete a specific chat by id
.
I was able to delete all documents using deleteMany
method, but can not delete a specific document by id.
export default async function handler(req: any, res: any) {
try {
const client = await clientPromise;
const db = client.db("mydb");
const { chatId } = req.body;
await db.collection("chats").deleteOne({
_id: new ObjectId(chatId),
});
res.status(200).json({});
} catch (error) {
...
}
}
On pressing a delete button I'm calling a function below:
const handleDeleteSingleChat = async () => {
await fetch(`/api/database/deleteChat`, {
method: "DELETE",
body: JSON.stringify({
chatId: chatId,
}),
});
};
My document in MongoDB looks like:
{
_id: ObjectId(64747668f6eefac44a882b35);
...
}
So far I've tried using different REST API methods. I've also tested chatId value and it works fine. I'm not exactly sure what to return in a handler so I just returned an empty object.
Note: I do not get any errors and network shows that fetch function was successful.
Update: I'm able to .deleteOne by writing document's string id directly, the problem is in chatId
value, but can't figure what.
export default async function handler(req: any, res: any) {
...
await db.collection("chats").deleteOne({
_id: new ObjectId("64747668f6eefac44a882b35"),
});
...
}