Build an Application in NodeJS Express and MongoDB - Part 1
Introduction
If you’re building applications using NodeJS and the Express framework, you may want to interact with a MongoDB database from your code. Fortunately, this task is easy to accomplish using the Mongoose package for Javascript. In this first article of our two-part series, we’ll show you how to create an application using NodeJS, Express and MongoDB. We’ll start by walking you through the process of installing the needed items and doing the necessary setup; after that, we’ll look at the code.
Prerequisites
Before we get started, let’s go over the prerequisites that need to be in place for this project:
Make sure that you have MongoDB installed and working on your machine. On Linux systems, you can use the command
mongod --version
to get the version number of your MongoDB installation.You’ll need to have some basic knowledge of Javascript, especially the NodeJS framework. You should also know how to use
NPM
, the package manager for NodeJS, to install themongoose
package. Mongoose is a tool for MongoDB that manages data relationships and validates schemas. It can be thought of as a layer that sits on top of the MongoDB driver for NodeJS.
Install NodeJS and NPM
We’ll need to install NodeJS before we can create our application with MongoDB. If you’re on a Windows or Mac operating system, you can click the download link for the Node installer.
Installing NodeJS in your linux system
If you’re running an Ubuntu or Debian distribution of Linux that uses the APT-GET repository, you can use the command shown below to install NodeJS:
1 | sudo apt-get install nodejs |
If you’re running a Red Hat distribution of Linux that uses the YUM repository, such as Fedora or CentOS, use this command to install NodeJS:
1 | sudo yum install nodejs |
Once you’ve completed the installation, you can verify the version number by typing node -v
in the terminal; similarly, you can use npm -v
to get the Node Package Manager version.
Create a database in MongoDB
Next, we’ll initialize and start the MongoDB interactive interface so that we can create a database:
1 | sudo service mongod start |
You’ll be prompted for a password. After entering it, use the command mongo
to start an instance of the Mongo shell.
To create a database in MongoDB, just type the command use
followed by a database name. It’s ok if this database name doesn’t yet exist– MongoDB will create it automatically and switch into it. You can see how it works below:
1 2 | use studentDB switched to db bookDB |
Start the project by creating a directory for the Node app
The first step in getting our project started is to set up the folder which will contain our Node application. We’ll create a directory in the terminal using the bash commands shown below, and then we’ll navigate into the directory:
1 | mkdir project && cd project |
Next, we’ll create a package.json
file. This file usually holds and manages the Node packages installed locally. It also includes the metadata of the project in the folder.
To create a new NodeJS application, we’ll run the command below:
1 | npm init -y |
NOTE: The -y
flag stands for yes
in response to the question asking if you still want to proceed with the command.
Install the NPM dependencies for the Node app
We’ll use the following command to install all the dependencies needed to set up our Node application:
1 | npm install --save express@4.17.1 express-handlebars@3.1.0 body-parser@1.19.0 mongoose@5.8.9 |
- Notice that we added the
@
sign before the number. This ensures that we get the latest version of the current npm package that we are installing.
Open your code editor
Before proceeding with the next steps, make sure you have a code editor that suits your needs. Some good choices include Sublime
, VSCode
and Atom
.
We’ll start by creating a model folder which will contain our db.js
file:
1 2 3 | > models > db.js > student.model.js |
Inside this db.js
file, we’ll create our database connection using the Mongoose package in NodeJS. Here’s how it’s done:
- First, create a constant variable that will require the Mongoose package:
1 | const mongoose = require('mongoose'); |
- Then, set the connection and create a callback function that will return the output:
1 2 3 4 5 6 7 | mongoose.connect('mongodb://localhost:27017/studentDB', { useUnifiedTopology: true, useNewUrlParser: true, useCreateIndex: true }, (err) => { if (!err) { console.log('Successfully Connected in MongoDB') } else { console.log('Syntax Error: ' + err) } }); // The destination file for the Book Schema require('./student.model'); |
- Keep in mind that the default port used for MongoDB is
27017
.
In the next section, we create the schema for the Node application:
student.model.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | // Create a constant mongoose variable const mongoose = require('mongoose'); // Create the variable book schema. var studentSchema = new mongoose.Schema({ stud_name: { type: String, required: 'This student needs name.' }, email_add: { type: String }, contact: { type: String }, country: { type: String } }); mongoose.model('Student', studentSchema); |
Finally, we start the Express server by creating our root file app.js
:
1 2 3 4 5 6 7 8 9 10 11 | // Add the destination file for the database require('./models/db'); // Create a constant variable for the express server const express = require('express'); var app = express(); // Create a listener for the port app.listen(5050, () => { console.log('Now starting at port: 5050'); }); |
To run your code, use the command node app.js
in your terminal. In your browser’s address bar, be sure to use the localhost port 5050
.
You’ll notice that there is an error getting the server– this occurs because we haven’t yet set up the route for the controller of the node application. We’ll tackle that task in the next article of the series.
Conclusion
When you’re building an application using NodeJS, Express and MongoDB, it’s important to make sure everything you need is installed and configured correctly. In this article, we covered those key steps in the process, and we also walked through the code needed to make the application work. The next article will pick up where we left off, detailing the remaining tasks needed to complete our NodeJS application.
Just the code
In this article, we reviewed quite a bit of code. Shown below is the sample code in its entirety:
db.js
1 2 3 4 5 6 7 8 9 | const mongoose = require('mongoose'); mongoose.connect('mongodb://localhost:27017/studentDB', { useUnifiedTopology: true, useNewUrlParser: true, useCreateIndex: true }, (err) => { if (!err) { console.log('Successfully Connected in MongoDB') } else { console.log('Syntax Error: ' + err) } }); require('./student.model'); |
student.model.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | const mongoose = require('mongoose'); var studentSchema = new mongoose.Schema({ stud_name: { type: String, required: 'This student needs name.' }, email_add: { type: String }, contact: { type: String }, country: { type: String } }); mongoose.model('Student', studentSchema); |
app.js
1 2 3 4 5 6 7 8 | require('./models/db'); const express = require('express'); var app = express(); app.listen(5050, () => { console.log('Now starting at port: 5050'); }); |
Pilot the ObjectRocket Platform Free!
Try Fully-Managed CockroachDB, Elasticsearch, MongoDB, PostgreSQL (Beta) or Redis.
Get Started