In this article, we are going to learn about one of the most used databases with Node Js,MongoDB.We will learn how to integrate Node JS and MongoDB,make basic APIs for CRUD operations and the pros and cons of using MongoDB as a Database.Now we assume that you have learnt about the basics of Node JS and having it in your systems, if not then go through this article.

This article is split into 2 parts:

What is MongoDB?

MongoDB is an open source database management system (DBMS) that uses a document-oriented database model which supports various forms of data. It is one of nonrelational database technologies which emerged in the mid-2000s under the NoSQL banner for use in big data applications and other processing jobs involving data that doesn’t fit well in a rigid relational model. Instead of using tables and rows as in relational databases, the MongoDB architecture is made up of collections and documents.

Installation

Check if your system is already having mongodb installed or not by typing this command in your terminal:

$  mongo –version

You will see the version of mongodb as output with some more details.If MongoDb is not installed on your machine, you should head to MongoDb Download Center, download and install the version compatible with your operating system before you continue.

Let’s Dive In

Create a new folder( “projectNew” or whatever you want) wherever you want and open that folder in your favourite text editor and open the integrated terminal if available else open the default terminal and head over to the directory you just created.Enter the following command and answer the questions to create the initial structure for your new project:

$  npm init

Now the next step would be to install driver dependencies.The three basic packages we are going to install are:

  • 1- ExpressJS: It’s a flexible Node.JS web application that has many features for web and mobile applications
  • 2- mongoose: the mongoDB ODM for Node.JS.
  • 3- body-parser: package that can be used to handle JSON requests.

These packages can be installed by following command in the terminal:

$  npm install –save express body-parser mongoose

Now create a file app.js in the same directory and require all the dependencies and assigning a port as stated below(you can copy paste this exact code):

const express = require(‘express’);
const bodyParser = require(‘body-parser’);
const app = express();
// initializing our app let port = 3000;
app.listen(port, () => {
console.log(‘Server is up and running on port number ‘ + port);
});

Save this and head over to terminal to test this by typing node app.js command.

By doing so you will see this in your terminal Server is up and running on port number 3000  And this shows that we have successfully created our app.

Constructing Architecture of our Project

Now in the same directory, I will create 2 subdirectories namely models and routes.

Create product.js in models and routes.js in routes directory respectively. After this step your directory architecture will look something like this. 

Now after this step, copy the below code in your models/product.js file.

First we started with requiring mongoose and then we define the schema for our model. Last thing is exporting the model so it can be used by other files in our project and with this we have made Schema of our project.

const mongoose = require(‘mongoose’);
const Schema = mongoose.Schema;
let ProductSchema = new Schema({
name: {type: String, required: true, max: 100},
price: {type: Number, required: true},
});
module.exports = mongoose.model(‘Product’, ProductSchema);

And after this step copy the following code in routes/routes.js file. This is the file that will include the routes of the products.

const express = require(‘express’);
const router = express.Router();
const Product = require(‘../models/product’);
// a simple test url to check that all of our files are communicating correctly.
router.get(‘/test’,(req,res)=>{
res.send(“Hello from routes.js”)
});
module.exports = router;

Now last step before we can test our application with this architecture is to update our app.js file,after which our app.js will look like this.

const express = require(‘express’);
const bodyParser = require(‘body-parser’);
const product = require(‘./routes/routes.js’);
//Imports routes from Products
const app = express();
// initializing our app
app.use(‘/products’,product);
let port = 3000;
app.listen(port, () => {
console.log(‘Server is up and running on port number ‘ + port);
});

Now start your app and Now head to your browser and try the following link: http://localhost:3000/products/test You will see the response as “Hello from routes.js” in your browser.Now we have our very first route working. Let’s get the rest working.

Connecting With MongoDB

We need to inform our app that it should be communicating with the database. Remember the ‘mongoose’ package we installed before? Now is the right time to use.All we have to head over to our app.js file and paste the following code in it just below the line where we initialized our app. Just remember to update the “url” variable with the connection string of your database (You can change “myproject1234” to any name ).

const mongoose = require(‘mongoose’);
var url = ‘mongodb://localhost:27017/myproject1234’;
const mongoDB =url;
mongoose.connect(mongoDB);
mongoose.Promise = global.Promise;
const db = mongoose.connection;
db.on(‘error’, console.error.bind(console, ‘MongoDB connection error:’));

And after this step we need to use bodyparser.Body Parser is an npm package that is used to parse the incoming request bodies in a middleware.Paste the following code just below the one you just pasted.

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

And with this our final app.js file will look like this:

const express = require(‘express’);
const bodyParser = require(‘body-parser’);
const product = require(‘./routes/routes’);
// Imports routes for the products
const app = express();
const mongoose = require(‘mongoose’);
var url = ‘mongodb://localhost:27017/myproject1234’;
const mongoDB =url;
mongoose.connect(mongoDB);
mongoose.Promise = global.Promise;
const db = mongoose.connection;
db.on(‘error’, console.error.bind(console, ‘MongoDB connection error:’));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(‘/products’, product);
let port = 3000;
app.listen(port, () => {
console.log(‘Server is up and running on port number ‘ + port);
});

(Note- Before creating APIs download postman in your system from here,it is a very useful tool in testing your APIs. Open the app, make sure it’s a GET request and type the following url ‘localhost:1234/products/test’. Just make sure that your server is still running on the port number 1234.).


That’s all I have and thanks a lot for reading. Please let me know if any corrections/suggestions. Please do share and comments if you like the post. Thanks in advance… 😉


Thanks Yash Kesarvani for helping us to grow day by day. He is expert in Node Js and loves to solve competitive programming.


Categories: Miscellaneous

0 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

Insert math as
Block
Inline
Additional settings
Formula color
Text color
#333333
Type math using LaTeX
Preview
\({}\)
Nothing to preview
Insert