在MongoDB中通过id删除一个文档时遇到了问题。

huangapple go评论75阅读模式
英文:

Having trouble .deleteOne by id in MongoDB

问题

I can help with the translation. Here is the translated code:

无法通过`id`在MongoDB中删除特定文档
在Next.js中我有以下处理程序以删除特定聊天通过`id`
我能够使用`deleteMany`方法删除所有文档但无法按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) {
    ...
  }
}

在按下删除按钮时我调用以下函数

const handleDeleteSingleChat = async () => {
  await fetch(`/api/database/deleteChat`, {
    method: "DELETE",
    body: JSON.stringify({
      chatId: chatId,
    }),
  });
};

我的MongoDB文档如下

{
  _id: ObjectId(64747668f6eefac44a882b35);
  ...
}

到目前为止我尝试了不同的REST API方法我也测试了`chatId`的值它工作正常我不确定在处理程序中应该返回什么所以我只返回了一个空对象

注意我没有收到任何错误网络显示fetch函数成功执行

更新我能够通过直接编写文档的字符串id来执行`.deleteOne`问题在于`chatId`的值但无法弄清楚是什么问题

export default async function handler(req: any, res: any) {
  ...

    await db.collection("chats").deleteOne({
      _id: new ObjectId("64747668f6eefac44a882b35"),
    });
  ...
}

Please note that the code is translated, but it's important to ensure that your project setup and dependencies are correctly configured for it to work as expected.

英文:

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"),
});
...
}

答案1

得分: 1

你的 fetch 调用很可能缺少了内容类型,因此后端将你的请求体转换为 JSON:

fetch(`/api/database/deleteChat`, {
  method: "POST",
  headers: {
    // 确保后端将请求体解释为 JSON
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    chatId: chatId,
  }),
});

此外,在 DELETE 方法的情况下,通常应将 id 传递到 URL 中,而不是在请求体中传递。参见:https://stackoverflow.com/questions/299628/is-an-entity-body-allowed-for-an-http-delete-request

看起来最近 Next.js 开始在 DELETE 方法的情况下忽略请求体,这导致了依赖于旧行为的开发者感到困惑:参见 vercel/next.js#49353

英文:

Your fetch call is very probably missing a content type, so that your body is converted to JSON in the backend:

fetch(`/api/database/deleteChat`, {
  method: "POST",
  headers: {
    // Ensure body will be interpreted as JSON by backend
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    chatId: chatId,
  }),
});

Furthermore, in the case of DELETE method, the id should typically be passed in the URL, rather than in the request body. See https://stackoverflow.com/questions/299628/is-an-entity-body-allowed-for-an-http-delete-request

Looks like Next.js started to ignore the request body in the case of a DELETE method only recently, leading to confusion among developers relying on the old behaviour: see vercel/next.js#49353

huangapple
  • 本文由 发表于 2023年5月29日 18:35:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/76356598.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定