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?
CodePudding user response:
As you can see from the official docs, deleteOne
returns an object with three properties:
ok
1
if no errorsdeletedCount
number of docs deletedn
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");
}