英文:
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
> 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();
});
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论