• 10 heures
  • Moyenne

Ce cours est visible gratuitement en ligne.

course.header.alt.is_video

course.header.alt.is_certifying

J'ai tout compris !

Mis à jour le 21/02/2022

Save and Retrieve Data

Using the  Thing  model from the previous chapter, we will leverage Mongoose to make saving and retrieving data to and from the database easier. Let's start by properly implementing a POST route.

Saving Things to the Database

Let see how we can save items in the Database!

To use the new Mongoose model in your app, you'll need to import it in the  app.js  file:

const Thing = require('./models/thing');

Now replace the logic in your POST route with the following:

app.post('/api/stuff', (req, res, next) => {
  const thing = new Thing({
    title: req.body.title,
    description: req.body.description,
    imageUrl: req.body.imageUrl,
    price: req.body.price,
    userId: req.body.userId
  });
  thing.save().then(
    () => {
      res.status(201).json({
        message: 'Post saved successfully!'
      });
    }
  ).catch(
    (error) => {
      res.status(400).json({
        error: error
      });
    }
  );
});

Now create a new instance of your  Thing  model, passing it a JavaScript object containing all of the information it needs from the parsed request body. That model has a  save()  method, which simply saves your  Thing  to the database.

The  save()  method returns a promise, so in your  then()  block, send back a success response. Then in your  catch()  block, send back an error response with the error thrown by Mongoose.

Retrieving the List of Things for Sale

Let see how to retrieve the list of things for sale from the database, in the next video!

Now you can implement your GET route to return all of the  Things  in the database:

app.use('/api/stuff', (req, res, next) => {
  Thing.find().then(
    (things) => {
      res.status(200).json(things);
    }
  ).catch(
    (error) => {
      res.status(400).json({
        error: error
      });
    }
  );
});

Use the  find()  method on your Mongoose model to return an array containing all of the  Things  in the database. Now, if you add a new  Thing , it should appear immediately on your Stuff for Sale page.

However, if you click on one of the  Things  , the single item view does not work, as it is trying to make a different GET call to find an individual thing. Let's implement that route now.

Retrieving a Specific Thing

Add another route to the app, just after the POST route:

app.get('/api/stuff/:id', (req, res, next) => {
  Thing.findOne({
    _id: req.params.id
  }).then(
    (thing) => {
      res.status(200).json(thing);
    }
  ).catch(
    (error) => {
      res.status(404).json({
        error: error
      });
    }
  );
});

In this route:

  • Use the  get()  method to only react to GET requests to this endpoint.

  • Use a colon in front of the dynamic segment of the route to make it accessible as a parameter.

  • Then use the  findOne()  method on your  Thing  model to find the single  Thing  with the same  _id  as the request parameter.

  • Thing  is then returned in a promise, and sent to the front end.

  • If no  Thing  is found or an error occurs, send a 404 error to the front end, along with the thrown error.

The app is really starting to take shape now. In the next chapter, we will implement the Modify and Delete buttons to complete the  Thing  part of the API.

Let's Recap!

  • Your  Thing  model's methods let you interact with your database:

    • save()  — saves a Thing

    • find()  — gets all the Things

    • findOne()  — gets one Thing, based on the comparison function you pass it (often using a Thing's unique identifier.

  • app.get() lets middleware only react to GET requests.

In the next chapter, you will learn how to use the rest of CRUD operations to update and delete data in the database! Let's go! 

Exemple de certificat de réussite
Exemple de certificat de réussite