Api for deleting

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

Api for deleting

问题

  1. const deleteContact = asyncHandler(async (req, res) => {
  2. const contact = await Contact.findById(req.params.id);
  3. if (!contact) {
  4. res.status(404);
  5. throw new Error("联系人未找到");
  6. }
  7. await Contact.remove();
  8. res.status(200).json();
  9. });
英文:
  1. const deleteContact=asyncHandler(async(req,res)=>{
  2. const contact=await Contact.findById(req.params.id);
  3. if(!contact){
  4. res.status(404);
  5. throw new Error("Contact Not foud");
  6. }
  7. await Contact.remove();
  8. res.status(200).json();
  9. });

I'm trying to write the end point of the deleting contact but I'm not able to delete by using the above query.

答案1

得分: 0

根据mongoose v7.3.1文档

> MongoDB驱动程序的remove()函数已被弃用,建议使用
> deleteOne() 和 deleteMany()。这是为了符合MongoDB CRUD
> 规范,该规范旨在为所有MongoDB驱动程序的CRUD
> 操作提供一致的API。

因此,使用deleteOne而不是remove,如下所示:

  1. await Contact.deleteOne({ _id: req.params.id });

更新后的代码:

  1. const deleteContact = asyncHandler(async(req, res) => {
  2. const contact = await Contact.findById(req.params.id);
  3. if (!contact) {
  4. res.status(404);
  5. throw new Error("联系人未找到");
  6. }
  7. await Contact.deleteOne({ _id: req.params.id });
  8. res.status(200).json();
  9. });
英文:

As per mongoose v7.3.1 document:

> The MongoDB driver's remove() function is deprecated in favor of
> deleteOne() and deleteMany(). This is to comply with the MongoDB CRUD
> specification, which aims to provide a consistent API for CRUD
> operations across all MongoDB drivers.

So use deleteOne instead of remove, as:

  1. await Contact.deleteOne({ _id: req.params.id });

Updated code:

  1. const deleteContact = asyncHandler(async(req,res) => {
  2. const contact=await Contact.findById(req.params.id);
  3. if(!contact){
  4. res.status(404);
  5. throw new Error("Contact Not found");
  6. }
  7. await Contact.deleteOne({ _id: req.params.id });
  8. res.status(200).json();
  9. });

huangapple
  • 本文由 发表于 2023年6月29日 02:38:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/76575870.html
匿名

发表评论

匿名网友

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

确定