Simple To-do List App with Node.js and MongoDB — Chapter 2

Diogo Pinheiro
6 min readMay 21, 2019

--

In the last chapter we created our project and made the GET and POST method, we also made our .ejs files so we could have a more friendly application.

In this chapter we we connect to our database and finish our app.

Creating cluster

  1. First we need to create an account at mongoDB Atlas

Then we need to create our cluster

After creating our cluster let´s add a new user and then our ip address to the whitelist.

Now we need to get our connection String so we go to the Cluster overview > connect > connect your application and then we have our string.

Connecting to database

Now we can connect to our database.

  1. First let´s add the following code to the index.js file and then create a file named .env, so we can have our string in a separate file.
const dotenv = require(“dotenv”);dotenv.config();

Add the following code to the .env file

DB_CONNECT = mongodb+srv://diogop:YOURUSER@YOURPASSWORD-1ylat.mongodb.net/test?retryWrites=true

Don’t forget to change the connection string by adding your username and your password that we created earlier.

2. Now we need to require mongoose so we can connect to our database.

Add the following code so we can make the connection to the database.

const mongoose = require("mongoose");
//connection to dbmongoose.set("useFindAndModify", false);mongoose.connect(process.env.DB_CONNECT, { useNewUrlParser: true }, () => {console.log("Connected to db!");app.listen(3000, () => console.log("Server Up and running"));});

We replaced our app.listen so our server would only run after the connection is made. We also add the mongoose.set(“useFindAndModify”, false), so we could avoid an error that we will have further.

Your file should look like this

If you have your server running with nodemon, we can see if our changes worked after saving.

CRUD Operations

In our project folder let´s create a new folder named models and then inside her a new file name TodoTask.js .

Inside TodoTask.js file let´s add the following code.

const mongoose = require('mongoose');const todoTaskSchema = new mongoose.Schema({content: {type: String,required: true},date: {type: Date,default: Date.now}})module.exports = mongoose.model('TodoTask',todoTaskSchema);

In here we made our collection schema and we exported so we could use it at index.js file.

Now we just have to require our model at the top of our index.js file

//modelsconst TodoTask = require("./models/TodoTask");

Your files should look like this

CRUD (CREATE)

Let’s change our POST method so when we click at the add button our app inserts data into the database.

//POST METHODapp.post('/',async (req, res) => {const todoTask = new TodoTask({content: req.body.content});try {await todoTask.save();res.redirect("/");} catch (err) {res.redirect("/");}});

Now if we add a task we can see it at our database in our collections.

CRUD (READ)

Now we need to read the data from the database so when we enter the page or when we add a new item we can see it at our app.

First we need to change our get method and then our todo.ejs file so we can see our data.

// GET METHODapp.get("/", (req, res) => {TodoTask.find({}, (err, tasks) => {res.render("todo.ejs", { todoTasks: tasks });});});

Change the following code at the todo.ejs file

<ul class="todo-list"><% todoTasks.forEach(details => { %><li class="todo-list-item"><div class="todo-list-item-name"><%= details.content %></div><a href="/edit/<%= details._id %>" class="edit"><span class="fas fa-edit"></span></a><a href="/remove/<%= details._id %>" class="remove"><span class="fas fa-times"></span></a></li><% }) %></ul>
Your files should look like this

Now we can see our data when we load the page and when we insert a new item.

CRUD (UPDATE)

First we need to create a new view in the views folder. I will call it todoEdit.ejs.

<!DOCTYPE html><head><title>Todo App</title><link rel="stylesheet" href="/static/stylesheets/style.css" type="text/css"><link href="https://fonts.googleapis.com/css?family=Baloo+Bhai|Candal|Chewy&display=swap" rel="stylesheet"><link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.8.2/css/all.css"integrity="sha384-oS3vJWv+0UjzBfQzYUhtDYW+Pj2yciDJxpsK1OYPAYjqT085Qq/1cq5FLXAZQ7Ay" crossorigin="anonymous"></head><body><div class="todo-container"><h2>To-Do List</h2><div class="todo"><form action="" method="POST" class="todo-header"><input type="text" name="content"><button type="submit"><span class="fas fa-plus"></span></button></form><ul class="todo-list"><% todoTasks.forEach(details => { %><% if (details._id == idTask) { %><li class="todo-list-item"><form action="/edit/<%= details._id %>" method="POST"><input type="text" value="<%= details.content %>" name="content"><button type="submit">Confirm</button><a href="/" class="cancel">Cancel</a></form></li><% } else { %><li class="todo-list-item"><div class="todo-list-item-name"><%= details.content %></div><a href="/edit/<%= details._id %>" class="edit"> <span class="fas fa-edit"></span></a><a href="/remove/<%= details._id %>" class="remove"> <span class="fas fa-times"></span></a></li><% } %><% }) %></ul></div></div></body>

Then we will create our UPDATE method in the index.js file.

//UPDATEapp.route("/edit/:id").get((req, res) => {const id = req.params.id;TodoTask.find({}, (err, tasks) => {res.render("todoEdit.ejs", { todoTasks: tasks, idTask: id });});}).post((req, res) => {const id = req.params.id;TodoTask.findByIdAndUpdate(id, { content: req.body.content }, err => {if (err) return res.send(500, err);res.redirect("/");});});

First we find our id and we render the new template. Then we update our task using the method findByIdAndUpdate.

If you have done everything right until now, you can see that we can edit our tasks.

CRUD (DELETE)

To end this tutorial we just have to do our DELETE method.

To do that we will use the method findByIdAndRemove.

//DELETEapp.route("/remove/:id").get((req, res) => {const id = req.params.id;TodoTask.findByIdAndRemove(id, err => {if (err) return res.send(500, err);res.redirect("/");});});

As you can see we are able to delete tasks now.

And that’s it, our app it’s finally done.

I hope you have done everything right and that your apps are working like they should.

--

--