I’m developing a web application using Express.js
and MongoDB
, and I’m implementing validation with express-validator
for updating or deleting resources. However, I have a concern about the performance implications of performing a validation check before making changes, as it involves accessing the database twice: once to check that the resource exists in the database and a second time to update/delete it. I’d like to understand the best practices in this scenario.
Here’s an example of my code. The param
and custom
functions come from express-validator
.
router.delete(
'/:id',
param('id').custom((id) => UsersMiddleware.validateUserExists(id)),
BodyValidationMiddleware.verifyBodyFieldsErrors,
UsersController.deleteById
);
My questions are:
- Is it considered a good practice to perform a validation check for resource existence before making updates or deletes?
- What are the potential performance implications of this approach, considering the additional database access?
2
Answers
I think, it’s not.
When you use update/delete operations in mongodb, it returns the number of documents that have changed. If it is 0, it means that the document did not exist before.
Therefore, your 1st request is unnecessary
// Router File
//Controller
// Services file
This is the method I use ,
I think this better than performing a db read and then updating / deleting.
but I am not sure about the performance aspect, i find this method simple and straightforward.