Hello everyone! Recently I have started an article series on the famous NodeJS framework called Express. So, this is another article on a very important concept needed when we work with Express? How to handle data with mongodb using Express? Here you can get to know the way to work with mongodb databases.

Without more discussions, I will move on to the explanation now.

First you need to create a project in NodeJS to build the Node server to run the application. Here I have given the link of my article to create a new project.
Link: https://salitha94.blogspot.com/2018/05/create-simple-web-server-with.html

I think you have the server now. Open the project in VS code or any other text editor. Navigate into the project using a terminal/cmd. We have to install a package called nodemon to make our work easier. Let me explain..
When we change the files in our projects, we have to save them and restart the server to catch the changes done. When we install nodemon, we do not have to do so. It auto refreshes the project files after changes.

npm install nodemon --save

I'm going to connect MongoDB in this article with Express. So we need a MongoDB database to connect. Open MongoDB console and create new database. If you do not installed MongoDB, refer this link.
Link: https://salitha94.blogspot.com/2018/06/introduction-to-mongo-db-and-installation.html

In MongoDB console, type this command. I'm going name my database as nodemongo.
use nodemongo

Now we are ready to go on.. Database is ready!!!

Then the most important part in connecting to the database using a MongoDB Library. There are several libraries available for MongoDB such as mongoose, mongojs..

I will use mongoose to connect with MongoDB. Install mongoose library to the project. Open cmd and type this command.
npm install mongoose --save

Next thing is to modify the server to include the DB connection. For this. open app.js file in your text editor and replace its code with this.

// Load express module
const express = require('express');

// Initialize app
const app = express();

// Mongoose connection
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/nodemongo');
const db = mongoose.connection;

// Check for DB connection
db.once('open', function(){
    console.log("Connected to MongoDB successfully!");
});
db.on('error', function(){
    console.log(err);
});

// Route for home
app.get('/', function (req, res) {
    res.send('hello world')
});

// Start server with port 3000
app.listen(3000, function(){
    console.log("Server started on localhost:3000");
});

Explanation :
After initializing app I have included some code lines. First the mongoose library is loaded. When we load it we have to give our DB location URL as a parameter. Then the connection is assigned to a variable. You can use var. But I used a const since it's not changing and a constant. Then we check the connection existence using a mongoose function. If we could connect successfully to the database after server is started, console will output "Connected to MongoDB successfully!" or otherwise the error will be displayed.

Now open terminal or cmd and type  nodemon  to start the server. Then console will display two lines if DB connection is also working perfectly.



So, guys I think you have followed me. If so, you are now ready to handle data with MongoDB! You can perform all CRUD functions with MongoDB using Express framework. My next article will be based on how to fetch data using Express from a MongoDB database. So, wait for it..I will come back soon.

Good Luck Guys!




6 Comments

  1. how does all of this work when mongodb connection is lost and re-established? How does express know that mongoDB connection is re-established? In the app I'm developing where I'm attempting to save data to mongodb database, if I start the express app before mongodb, or mongodb connection is lost and than re-established, express doesn't re-start nor are any of my inputs saved to mongodb (and express still posts a 200 status code (ie, everything is ok). One recommendation I've seen is to add a mongoose event listener (such as mongoose.connection.on) and initialize express (var/const app = express()) inside that event listener. Do you have further information on such an approach?

    ReplyDelete
    Replies
    1. Sorry for late reply! Usually you must start mongodb before you start your express app! Because mongodb has to be up and running to be used in your express app. I have done the same thing you have told. db variable is assigned to mongoose.connection in order to listen to the db connection created (mongoose.connection). Then I have taken db.on => mongoose.connection.on

      Delete
  2. Thank you very much for your feedback Jack :D

    ReplyDelete