Section 27 – Lessons 359 & 360 – Complete 2020 Web Development Bootcamp

Lesson 359 – Rendering Database Items in the ToDoList App

In order to find data in the mongoDB database using Mongoose, you can use the .find() method.

The challenge is to log all of the information from the items collection by inserting the appropriate code in the app.js file.

This is the code that is inserted in the app.get(“/”) method to complete the challenge –

Item.find({}, function(err, foundItems) {
  
res.render("list", {listTitle: "Today", newListItems: foundItems});

The new app.get(“/”) method code is –

app.get("/", function(req, res) {

    Item.find({}, function(err, foundItems) {
  
    res.render("list", {listTitle: "Today", newListItems: 
    foundItems});
  
});

The next challenge it so refactor this for loop in the list.ejs file into a forEach loop –

<% for (let i=0; i<newListItems.length; i++) { %>
      <div class="item">
        <input type="checkbox">
        <p><%=  newListItems[i].name  %></p>
      </div>
      <% } %>

The forEach loop to satisfy this challenge is –

<% newListItems.forEach(function(item) { %>
     
        <div class="item">
        <input type="checkbox">
        <p><%=  item.name  %></p>
        </div>

<% }) %>

In order to not add the items in the defaultItems array every time the server is restarted, you have to refactor the app.get(“/”) method code to insert the Item.find() method inside of the app.get(“/”) method code like this –

app.get("/", function(req, res) {

    Item.find({}, function(err, foundItems) {

    if (foundItems.length === 0) {


      Item.insertMany(defaultItems, function(err) {
      if (err) {
      console.log(err);
      } else {
      console.log("defaultItems array inserted into database");
      }   
    });

      res.redirect("/");

    } else {
      res.render("list", {listTitle: "Today", newListItems: foundItems});
    }
 });
});

Lesson 360 – Adding New Items to our ToDoList Database

In this lesson, you have to refactor the app.post(“/”) route so that when a new item is added to the todo list it is posted to the home page.

The first step is to delete this code in the app.post(“/”) route –


  if (req.body.list === "Work") {
    workItems.push(item);
    res.redirect("/work");
  } else {
    items.push(item);
    res.redirect("/");
  }

The next step is to refactor the app.post(“/”) route code like this –

app.post("/", function(req, res){

  const itemName = req.body.newItem;

  const item = new Item({
    name: itemName
  });

  item.save();

  res.redirect("/");

});