Build a notes web application using Node.js, Express and MongoDB Part 1

In this tutorial we will build a simple notes application using Node.js and React. First we will build a CRUD Rest API that can create, retrieve, update and delete Notes using Node.js, Express and MongoDB database. Express is a popular web framework for Node.js that supports routing and middleware to respond to incoming requests. For the object data model, we use Mongoose that provides a schema-based solution to model our application data.

Application that we will build looks like this:

The CRUD Rest API overview

First, we start creating an Express web server, then we will add configuration to connect to MongoDB database, create a Note model with Mongoose and define routes for handling all CRUD operations.

The following table shows an overview of the endpoints that will be exposed after we have created the Rest APIs:

GET            api/notes         get all Notes

POST         api/notes         add a new Note

PUT            api/edit            update a Note

DELETE      api/delete        remove a Note

Create Node.js App and setup Express web server

First create a folder by running the following command:

mkdir nodejs-express-mongodb
cd nodejs-express-mongodb

Then run npm init to initialize the app with a package.json file. Then we need to install necessary dependencies: express, mongoose and body-parser.

Run the following command:

npm install express mongoose body-parser --save

Now we need to create an index.js file. Paste the following content inside it:

const bodyParser = require("body-parser");

const app = express();

// Middlewares are used here

app.use(bodyParser.json());

app.use(express.urlencoded({ extended: false }));

const PORT = 5000;

app.listen(PORT);

What the code does:

We are importing express and body-parser modules. Express is for creating a web server that handles different incoming request. The body-parser helps us to parse the request and create the request body object.

The app.use(bodyParser.json()) tells the web server that you want to post a json data in the request, and bodyParser.urlencoded({extended: false})) tells the web server that you will be encoding the parameters in the URL.

The last command will tell the web server to listen on port 5000 for incoming requests.


Setup MongoDB database and Mongoose

First you should install MongoDB on your machine. The instructions can be found here:

https://docs.mongodb.com/manual/installation/

Next, create a folder named config in the app folder and create a file named key.js as follows:

module.exports = {
  mongoURI: mongodb://localhost:27017/noteApp_db
};


Define the Note model with Mongoose

Create a file named Note.js in app/models folder with the following content:

const mongoose = require("mongoose");
const { Schema } = mongoose;

const noteSchema = new Schema({
  title: String,
  body: String,
  archieved_at: Date,
  created_at: Date,
  updated_at: Date,
  deleted_at: Date,
  starred: Boolean
});

mongoose.model("note", noteSchema);

This Mongoose Model represents a Notes collection in MongoDB database. Each field will be generated automatically for each Notes document. This is the concept of Object-Document-Mapping (ODM) and can make life easier.


Connect to MongoDB and defining the routes

To connect to MongoDB you need to call connect() method in index.js like this:

const keys = require("./config/keys");
require("./models/Note");

// connect to mongoDB
mongoose.connect(keys.mongoURI);

const app = express();
…

We need to handle different requests from the client, therefore we need to tell the server how it will respond to the requests by setting up the routes.

These are our routes as we described previously:

/api/notes: GET, POST

/api/edit: PUT

/api/delete: DELETE

Now, create a noteRoutes.js file inside app/routes folder with following content:

const mongoose = require("mongoose");

const Note = mongoose.model("note");

module.exports = app => {
  // Read notes
  app.get("/api/notes", async (req, res) => {
    const notes = await Note.find();

    res.send(notes);
  });

  // Create a note
  app.post("/api/notes", async (req, res) => {
    const note = new Note({
      title: req.body.title,
      body: req.body.body,
      created_at: Date.now(),
      updated_at: Date.now(),
      deleted_at: null,
      archieved_at: null,
      starred: false
    });

    await note.save((err, note) => {
      res.send(note);
    });
  });

  // Delete a note
  app.delete("/api/delete/:id", (req, res) => {
    const _id = req.params.id;

    Note.findByIdAndRemove(_id, (err, data) => {
      if (err) {
        return res.sendStatus(500);
      }
      return res.sendStatus(200);
    });
  });

  // Update a note
  app.put("/api/edit/:id", async (req, res, next) => {
    const _id = req.params.id;

    const filter = {};
    filter["_id"] = _id;

    const updatedNote = await Note.findOneAndUpdate(filter, req.body, {
      new: true
    });

    res.send(updatedNote);
  });
};

We use the Mongoose Note Model to be able to use the built in CRUD functions:

• create a new Note: Note.save()

• retrieve all Notes: Note.find()

• update a Note by id: Note.findOneAndUpdate(filter, data)

• delete a Note: Note.findByIdAndRemove(id)

We also need to include noteRoutes in the index.js file before app.listen():

…
require("./routes/noteRoutes")(app);

const PORT = 5000;
app.listen(PORT);


Summary

In this tutorial, we have learned how to create Node.js Rest API with an Express web server and also learned how to connect to MongoDB database, created a Mongoose Model, and learned how to define routes for handling all CRUD operations. In the next part of this tutorial we will learn how to build the client in React and Redux.