我陷入了关于Mongoose的deleteOne方法的问题。
问题如下:
The code that I wrote is here.
是否有可能以某种方式得到错误?
如果您能解决这个问题,我将不胜感激。先感谢您。
最佳答案
Mongodb(您的 Mongoose 使用的npm)在删除具有键的文档时返回以下deleteOne:
{ "acknowledged" : true, "deletedCount" : 1 }
以防万一,当您删除已经删除的同一文档时,它会返回:{ "acknowledged" : true, "deletedCount" : 0 }
因此,如下修改您的代码:await Post.deleteOne({_id: postId}, (err, d) => {
if (err) return res.status(400)
if (d.acknowledged && d.deletedCount == 1)
console.log("Deleted Successfully") // Use your response code
else
console.log("Record doesn't exist or already deleted") // Use your response code
})
Mongo Shell输出供引用:> db.post.deleteOne({"_id" : ObjectId("5e8478d86c193bc19f5e4112")})
{ "acknowledged" : true, "deletedCount" : 1 }
> db.post.deleteOne({"_id" : ObjectId("5e8478d86c193bc19f5e4112")})
{ "acknowledged" : true, "deletedCount" : 0 }