Using Mongo DB with Node JS

Vamsi Krishna Karanam
5 min readMay 25, 2020

--

In the last article, I talked about Mongo DB installation, and how to use it within the Mongo shell. If you haven’t read it yet, I strongly recommend you go through it and then come back here. Assuming that you have everything set up as mentioned in the last article, now I’m gonna talk about how Mongo DB when combined with any web framework like Node.js, will become a very powerful backend system. So without further ado let’s jump into it.

Node.js is a free, open-source Javascript runtime built on Chrome’s V8 Javascript engine. It is basically used as a server environment and also supports various browsers. It is one of the most used Javascript runtimes in the developer community.

These are the most wanted web frameworks according to the survey done by StackOverflow. This shows how web developers love to work with the Node.js framework. With that said, we can now start our tutorial on how Mongo DB can be combined with Node.js in backend development.

In order to use Node JS we have to first install it. You can download install Node from their official website. Once you’re done check if the installation is successful by opening a new command prompt and giving the command :

node --version

If it returns the version of Node that you’ve installed, you’re good to go. If not try setting the environment variables for Node manually. With Node installed it should have also installed NPM (Node package manager) with it. Verify this by giving the command :

npm --version

If it returns the version, it means we have successfully installed Node and NPM (even if the version is different from that of the node). By using NPM we can install various node projects. For this tutorial, we are gonna use Express (to set up the local server), Mongo packages.

First, create a directory to hold all our project files in your preferred location. Now cd over to that directory. Here is where we are gonna initialize our first Node.js project. To do so, give the command :

npm init

which will return the following :

This utility will walk you through creating a package.json file.
It only covers the most common items, and tries to guess sensible defaults.
See `npm help init` for definitive documentation on these fields
and exactly what they do.
Use `npm install <pkg>` afterwards to install a package and
save it as a dependency in the package.json file.
Press ^C at any time to quit.
package name: (<yourFolderName>)

Give the desired name for your project, or just hit enter to set the name to folder name. Do the same for version, description, entry point, test command, git repository, keywords, author, and license. You will then arrive at :

About to write to C:\Users\User1\Desktop\MyFirstNodeProject\package.json:{
"name": "article",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC"
}
Is this OK? (yes)

Hit enter. Now you will have a package.json file created in the same directory. Open this project folder in a code editor of your choice (Visual Studio Code/ Atom etc.) If you don’t have any it’s not a problem. You can also edit your files in notepad. But I strongly recommend you download one of the code editors mentioned above, as they will be very helpful in organizing and writing code. In the editor create a new file named index.js at the same level. Now it’s time to install our node packages. Open the command prompt and issue the following command :

npm i express mongodb

which even though takes some time, installs those two packages and returns the confirmation message which looks something like this, depending on the version installed in your machine:

npm notice created a lockfile as package-lock.json. You should commit this file.
npm WARN article@1.0.0 No repository field.
+ mongodb@3.5.7
+ express@4.17.1
added 66 packages from 45 contributors and audited 66 packages in 37.443s
found 0 vulnerabilities

Now open the index.js file in your code editor. First we are gonna set the server up and running using express. To do this write the following code into index.js file.

const express = require("express");
const app = express();
app.listen(3000, function(){
console.log("Server has been started on port 3000");
});

To check if the code is running as it is intended to, open the command prompt and run it using :

node index.js

It should say “Server has been started on port 3000”. Congratulations! You have successfully set up your own local server. Now to give some response to the user, let’s create a get method above our listen method in index.js file as follows :

app.get("/", function(req, res){
res.send("<h1>Hello world</h1>");
});

This will render the text “Hello world” into the response file. To have a better understanding run the file again and open any browser of your choice. Type the URL localhost://3000. You can now be able to see Hello world in large bold letters. Now let’s see how we can connect to MongoDB and send that data as a response to the browser. Create a variable that requires the installed mongodb package as :

const mongodb = require("mongodb");

Now to create a new database, we have to create a new MongoClient and a local URL for the MongoDB collection, and finally, a new collection to store the data, which is exactly done by the following code :

var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/mydb";

MongoClient.connect(url, function(err, db) {
if (err) throw err;
console.log("Database created!");
dbo.createCollection("customers", function(err, res) {
if (err) throw err;
console.log("Collection created!");
db.close();
});
db.close();
});

Now let’s insert one document into our customers collection. In order to do this, we have to create a new JSON object and call the insertOne() function on the customers collection as follows :

  var myobj = { name: "Vamsi", address: "Highway 37" };
dbo.collection("customers").insertOne(myobj, function(err, res) {
if (err) throw err;
console.log("1 document inserted");
db.close();
});

Now let us retrieve this data to show in our response. For this we are using the findOne() method on customers collection.

dbo.collection("customers").findOne({}, function(err, result) {
if (err) throw err;
var CustomerName = result.name;
db.close();
});

Now let’s change our response in app.get() method so that it will display the customer name as a response to the get call.

app.get("/", function(req, res){
res.send("<h1>Welcome <h1>"+customerName);
});

Now if you go ahead and run the index.js file and open the localhost://3000 you will see the message saying “Welcome Vamsi” or whichever name you have given in the insertOne() method. The final code looks like this :

const express = require("express");
const app = express();
const mongo = require("mongodb");
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/mydb";
MongoClient.connect(url, function(err, dbo) {
if (err) throw err;
console.log("Database created!");
dbo.createCollection("customers", function(err, res) {
if (err) throw err;
console.log("Collection created!");
db.close();
});
var myobj = { name: "Vamsi", address: "Highway 37" };
dbo.collection("customers").insertOne(myobj, function(err, res) {
if (err) throw err;
console.log("1 document inserted");
db.close();
});
dbo.collection("customers").findOne({}, function(err, result) {
if (err) throw err;
var CustomerName = result.name;
db.close();
});
dbo.close();
});
app.get("/", function(req, res){
res.send("<h1>Welcome <h1>"+customerName);
});
app.listen(3000, function(){
console.log("Server has been started on port 3000");
});

That’s all for this tutorial. If you have reached here following all the steps, thank you for spending your time on my article. Feel free to comment your thoughts/questions/suggestions. In the next article, we will see how we can refractor and reduce the amount of code we wrote here just by using a simple node.js package which will take most of the weight for us. See you there!

--

--