Learn Node.js by example — Part 2

Eniola Lucas Fakeye
4 min readOct 8, 2017

This is the second part of the ‘Learn Node.js by example’ series. In this series, we are going to learn how to set up and use a MongoDB database and create RESTful API through which frontend clients will communicate with the serve.

Mongoose and Body parser installation.

We will navigate to our project folder on the command line and run npm install mongoose body-parser --save command to install mongoose and body parser.

Mongoose is a node package that manage connection to a MongoDB database, it also handle storage, retrieval and elimination of data.

We expect the front-end client to send data to the server at some point in time. Therefore, there is need to find a way to extract this information from the HTTP request object. Body parser will help us do that.

If you don’t have the latest version of Node.js installed on your machine you need to include the ` --save` flag to your npm install commands so that all the package being used in the project will be tracked in the package.json file.

Setting up MongoDB

Setting up a MongoDB locally can sometimes feel like drudgery. In order to avoid this we will host our database remotely on mLab. mLab is a MongoDB based database-as-a-service platform.

Sign up and supply the necessary information to get started. MongoDB is a NoSQL database (basically, a database without tables). It stores data as JSON objects in a document.

When you are done with registration, click on the create new button on the top right side of the page and follow the instruction to create a new MongoDB deployment / database.

The name of your new MongoDB deployment should appear on the list of MongoDB deployments. Click on it and select the user tab on the new page to create a new user. You need to create a user to access the database.

We can now connect to our database with the URL above the tabs by replacing <dbuser> with the username of the user we’ve just created and <dbpassword> with the password of the user.

Creating Schema And Model.

Before we start storing data in the database we need to define the structure of each unit of similar data set i.e the schema and a model that will enable us to perform database operation on the data set.

We start by creating a new file in the root directory, named models.js. Copy and paste the block of code below into the models.jsfile.

var mongoose = require('mongoose');// define schema as mongoose schema classlet Schema = mongoose.Schema;// instantiate the schema classlet TodoSchema = new Schema({todo_title: String,todo_description: String,todo_added_at: {type: Date, default: Date.now}});// create a model from the schemalet TodoModel = mongoose.model('TodoModel', TodoSchema);// export model as a modulemodule.exports = TodoModel;

In the code block above, we import the mongoose npm package into our file. This gives us access to the schema class which was used to define our schema by instantiating the Schema class and passing an object literal that contains the structure of our database to the constructor. We created a model from the schema and export our model as a Javascript module to make it reuse-able / accessible in other files.

Once we are done with this, we’ll import TodoModel in index.js file and connect to MongoDB. Behold the new look of index.js :

// import express framework using es6 syntaxvar express = require('express');//import mongoose and TodoModelvar mongoose = require('mongoose');var TodoModel = require('./models');// create an instance of express called appvar app = express();// specify the port number through which your app will be servedconst PORT = 9000;// connect to mongodbmongoose.connect('mongodb://USERNAME_HERE:PASSWORD_HERE@XXXXXXXX.mlab.com:XXXXX/todo-list')// use express get method to create aapp.get('/', function(req, res) {res.status(200).send("Hello World!");});// listen to request sent to the portapp.listen(PORT, function() {console.log("Server running on Port", PORT);});

Keeping our connection parameters in index.js file is a bad idea together with not providing a means of handling connection error. However trying to cater for all things we make this series longer than it is already. You can read more on how to connect to a MongoDB database with mongoose here.

Thanks for reading. Part 3, is the last part, please be on the lookout.

If you like this article, please, give a clap or ‘few’ to show appreciation.

--

--

Eniola Lucas Fakeye

Software Engineer | Startup Enthusiast | Passionate Learner