skip to Main Content

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:

  1. Is it considered a good practice to perform a validation check for resource existence before making updates or deletes?
  2. What are the potential performance implications of this approach, considering the additional database access?

2

Answers


  1. 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

    Login or Signup to reply.
  2. // Router File

      router.put(
       '/update/:id',
        guard.isAuthorized(['admin']),
        middleware.updateValidation,
        controller.updateById
    )
    

    //Controller

     /**
       * Update
       */
    updateById:async(req,res)=>{
        try {
            const update = await ContactUsServices.update(req);
            if(!update){
                return  commonResponse.notFound(res,"DATA_NOT_FOUND",400)
            }
            commonResponse.success(res, "SINGLE_ENTRY_OF_CONTACT_US_DATA_UPDATED", 200, update);
        } catch (error) {
            return commonResponse.CustomError(res, "CONTACT_US_DATA_NOT_UPDATED", 400, error,"Error");
        }
    },
    

    // Services file

     /** 
     *Update
     */
    
     exports.update = async(req)=>{
       return await ContactUsModel.findByIdAndUpdate({_id:req.params.id},{$set:req.body},{new:true}).lean();
    }
    

    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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search