Api for deleting

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

Api for deleting

问题

const deleteContact = asyncHandler(async (req, res) => {

    const contact = await Contact.findById(req.params.id);

    if (!contact) {
        res.status(404);
        throw new Error("联系人未找到");
    }

    await Contact.remove();
    res.status(200).json();
});
英文:
const deleteContact=asyncHandler(async(req,res)=>{

    const contact=await Contact.findById(req.params.id);

    if(!contact){
        res.status(404);
        throw new Error("Contact Not foud");
    }

    await Contact.remove();
    res.status(200).json();
});

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,如下所示:

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

更新后的代码:

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

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:

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

Updated code:

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

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:

确定