Is it possible to get a detailed query when delete operation fails?


I am doing a delete operation with a filter of 2 fields:

const query = await Flow.deleteOne({
    _id: flowId,
    permissions: currentUser!.id,

Then I check the query object that returns from this operation to determine whether the operation was successful or not:

if (!query.deletedCount) {
    throw new BadRequestError("Flow not found");

The problem is that I cant know if the operation failed because the flowId is wrong (first filter field) or the user don’t have permissions (second filter field).

Is there an option to get a more detailed query result in mongoose?


As you can see from the official docs, deleteOne returns an object with three properties:

  • ok 1 if no errors
  • deletedCount number of docs deleted
  • n number of docs deleted

If you need to investigate the reasons for the failure you could query the database in case of error, something like:

if (!query.deletedCount) {
    const flow = await Flow.findById(flowId);
    // wrong `flowId`
    if (!flow) throw new BadRequestError("Flow not found");
    // otherwise, user don't have permission
    throw new BadRequestError("Unauthorized");

Answered By – lpizzinidev

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published