17. Patching and Deleting a User


Patching a User Document

Per the API specifications the PATCH /user endpoint should allow the user to modify the following fields in their user document:

  • first name
  • last name
  • username
  • email
  • password

To accomplish this the client will send a request with a body similar to POST /user except it will contain only the information that the user would like to change.  The endpoint will first verify that the client has not sent properties that are not modifiable.  If all of the properties that the client sent are modifiable then the endpoint will update the user document and save the document in the collection.

Below is code for the endpoint that does the job.

router.patch('/user', auth, async (req, res) => {
    const user = req.user
    const mods = req.body

    const modifiable = ['username', 'password', 'firstName', 'lastName', 'email']

    try {
        // check that all the keys sent are modifiable
        const keys = Object.keys(mods)
        const isValid = keys.every((key) => modifiable.includes(key))

        if (!isValid) {
            return res.status(400).send('One or more invalid properties.')
        }

        // set the new values in the user doc
        keys.forEach((key) => user[key] = mods[key])
        await user.save()

        res.send(user)
    }
    catch (err) {
        console.log(err)
        if (err.code === 11000) {
            console.log('Duplicate account')
            return res.status(409).send(err)
        }
        else if (err.name === 'ValidationError') {
            console.log('Validation error')
            return res.status(400).send(err)
        }
        else {
            res.status(500).send(err)
        }
    }
})

Let’s walk through the code.

We see on line 1 the method and path. We also see that we are using the auth middleware,  which allows us to grab the user document belonging to the user who is making the request on line 2.

On line 3 we get the JSON object sent by the client and store it in a variable named mods.

On line 5 we specify all of the properties that we’ll allow the user to modify with this endpoint by listing their keys in an array.

Next, on line 8 we retrieve all of the keys from the object sent by the client.

One line 9 we verify that every key sent by the client is in set of modifiable keys.  If not, then we return a error (lines 11-13).

If all of the properties that the client sent are modifiable, then we update the user document (line 17) and save the changes in the collection (line 18).

Test With Postman

Create a request in Postman and use it to test the endpoint.  Perform multiple test:

  • test modifying multiple properties,
  • test changing properties with values that don’t pass the validators,
  • try to set unique properties to values that already exists in the collection.

Deleting a User Document

When a user delete’s their account they expect that all of the information about them is removed from the system.  At this point the only a user has input is in their user document, so when a user requests that their account be deleted we’ll delete the document associated with them from the User collection.  Later when we add other capabilities, we revisit this endpoint.

router.delete('/user', auth, async (req, res) => {
    const user = req.user

    try{
        await user.deleteOne()

        res.send()
    }
    catch (e) {
        res.status(500).send
    }
})

Test With Postman

Create a request in Postman to verify that the endpoint is working properly. 

Create multiple user accounts (hit the ellipsis next to the endpoint to create multiple examples).  Then delete one using the endpoint.  Use Compass to verify that the document has been deleted.

Push Your Changes to GitHub

Git add, git commit, and git push.