0

I have got stuck in a problem about deleteOne method of Mongoose.

The problem is as follows:

  1. deleted a document by using deleteOne() with a key.
  2. tried to delete the same document by using deleteOne() with the same key again, and then the method didn't return any error.

The code that I wrote is here.

Is it possible to get an error somehow?

I would be grateful if you could solve this problem. Thank you in advance.

1 Answers1

2

Mongodb (npm used by you mongoose) returns following with deleteOne when deleting a document with key and it exists:

{ "acknowledged" : true, "deletedCount" : 1 }

In case, when you delete the same document which was already deleted it returns:

{ "acknowledged" : true, "deletedCount" : 0 }

So, modify your code as below:

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 Output for reference:

> db.post.deleteOne({"_id" : ObjectId("5e8478d86c193bc19f5e4112")})
{ "acknowledged" : true, "deletedCount" : 1 }
> db.post.deleteOne({"_id" : ObjectId("5e8478d86c193bc19f5e4112")})
{ "acknowledged" : true, "deletedCount" : 0 }
Shreeram K
  • 1,719
  • 13
  • 22