• 10 hours
  • Medium

Free online content available in this course.

course.header.alt.is_video

course.header.alt.is_certifying

Got it!

Last updated on 2/21/22

Complete the CRUD With Update and Delete

Update an Existing Thing

Let's add another route to the app, just below the individual GET route. This time, it will respond to PUT requests:

app.put('/api/stuff/:id', (req, res, next) => {
  const thing = new Thing({
    _id: req.params.id,
    title: req.body.title,
    description: req.body.description,
    imageUrl: req.body.imageUrl,
    price: req.body.price,
    userId: req.body.userId
  });
  Thing.updateOne({_id: req.params.id}, thing).then(
    () => {
      res.status(201).json({
        message: 'Thing updated successfully!'
      });
    }
  ).catch(
    (error) => {
      res.status(400).json({
        error: error
      });
    }
  );
});

Here, you leverage the  updateOne()  method on the  Thing  model. It allows you to update the  Thing  corresponding to the object you pass as a first argument. Use the  id  parameter passed in the request and replace it with the  Thing  passed as a second argument.

Try out the new route by clicking on a  Thing  in the app, then its Modify button, and submitting a modified  Thing !

Deleting a Thing

Time to add one last route — DELETE:

app.delete('/api/stuff/:id', (req, res, next) => {
  Thing.deleteOne({_id: req.params.id}).then(
    () => {
      res.status(200).json({
        message: 'Deleted!'
      });
    }
  ).catch(
    (error) => {
      res.status(400).json({
        error: error
      });
    }
  );
});

The model's  deleteOne()  method works like  findOne()  and  updateOne()  , in that you pass it an object corresponding to the document you want to delete. Then send either a success or a failure response to the front end as appropriate.

Congratulations!  The app now allows the full customer journey through adding, viewing, updating, and deleting things for sale!

Let's Recap!

  • app.put()  and  app.delete() middleware react to PUT and DELETE type requests.

  • Your Thing model's updateOne() and delete() methods let you update or delete  Things  in the database.

What You've Learned in This Part of the Course

  • You set up your MongoDB database and connected it to your Express app.

  • You used Mongoose to create a data model to facilitate database operations.

  • You implemented CRUD routes in your Express app, which leveraged your Mongoose data model, rendering your app fully dynamic.

In the next part of the course, we will cover an extremely important topic: security. 

Example of certificate of achievement
Example of certificate of achievement