Section 27 – Lesson 358 – Complete 2020 Web Development Bootcamp

Lesson 358 – Connecting ToDo List Project with Mongoose

The first step in adding a database to the ToDo List project is to delete the existing arrays in the app.js file. These lines of code should be deleted –

const items = ["Buy Food", "Cook Food", "Eat Food"];
const workItems = [];

The next step is to install mongoose. In the terminal, you type –

npm i mongoose

The next step is to create a constant called “mongoose” which will require the mongoose package. This is the code –

const mongoose = require("mongoose");

Then we have to create a new database inside mongoDB. To do this, you first have to specify which database you want to connect to using this code –

mongoose.connect("mongodb://localhost:27017/todolistDB", {useNewUrlParser: true, useUnifiedTopology: true});

The next step is to create a new items schema. The challenge is to create this schema with one filed called “name” with a data type of string.

This is the code which completes the challenge –

const itemsSchema = new mongoose.Schema {
  name: String
};

The next challenge is to create a new mongoose model based on the itemsSchema.

This code completes the challenge –

const Item = mongoose.model("Item", itemsSchema);

Then you have to create three new items using the mongoose.model that was just created in the last challenge.

The code to create the three new items is –

const item1 = new Item ({
  name: "Welcome to your todo list!"
});

const item2 = new Item ({
  name: "Hit the + button to add a new item."
});

const item3 = new Item ({
  name: "<-- Hit this to delete an item."
});

The next step is to put those documents into an array. This code creates the array –

const defaultItems = [item1, item2, item3];

You can then use the mongoose .insertMany() method to insert all of the items in the defaultItems array into the mongoDB database.

This code inserts the defaultItems array in the database –

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