How can connect to the MongoDB through Node.js?

Hey guys,
Today I am going to show you how connect to MongoDB through Node.js. Please follow the below steps:
Note: for those that do not know how to install and use MongoDB please what this Video or ready this post
Note: I am using Webstorm to develop Node.js, you can install 30 days trail version and if you found it is good then buy it or you can use Code IDE which is an IDE that is provided by Microsoft and it is free 
If you use Webstorm, it creates everything for you and you only need to change the code and no need to be worry about the packages and other settings that normally needed for Node.js, here is my Webstorm screen:

There are different libraries that can help you to connect to MongoDB, for this tutorial I am using monk, which is simple and very light.
1. Add these few lines of code to app.js file :


var mong = require('mongodb'); // we import MongoDB
// library to our project
var monk = require('monk');// we create an object 
//from monk liberay in order to connect to MongoDb
var db = monk('localhost:27017/userlist');// we create an database 
//object which is connected to our ruing MongoDB instance

2. In the next step we need to set db in all requests that come to our server, it is a bit different with what we have done in ASP.net. you must be aware that concept in Nodde.js is very different with what you know in ASP.net or even Java.


app.use(function(req,res,next){
req.db = db;
next();
});

3. This few lines of code must be add before:


app.use('/', routes);
app.use('/users', users);

4. After these two simple steps, our app.js is ready to connect to MongoDB and gave service to rest of application. Now we need to add two functions to our route and create two more views in order to show the result and get data from user. Direct go to the route folder and open index.js and add these two functions:

Get data:


router.get('/userlist',function(req,res){
var db= req.db;
var collection=db.get('testcollection');
collection.find({},{},function(e,docs){

res.render('userlist',{"userlist":docs

});

});

});

Receive post request and insert in database.

router.post('/adduser', function(req, res) {

// Set our internal DB variable
var db = req.db;

// Get our form values. These rely on the "name" attributes
var userName = req.body.username;
var userEmail = req.body.useremail;

// Set our collection
var collection = db.get('testcollection');

// Submit to the DB
collection.insert({
"name" : userName,
"email" : userEmail
}, function (err, doc) {
if (err) {
// If it failed, return error
res.send("There was a problem adding the information to the database.");
}
else {
// And forward to success page
res.redirect("userlist");
}
});
});

We need two different views for these two functions, To add view, straight go to the view folder, copy and paste index.jade and change name to userlist ‘and do the same and name it adduser.

Open userlist and copy this code there:

extends layout

block content
h1.
User List
ul
each user, i in userlist
li
a(href="mailto:#{user.email}")= user.name

Open adduser and copy this code there:

extends layout
block content
h1= title
form#formAddUser(name="adduser",method="post",action="/adduser")
input#inputUserName(type="text", placeholder="username", name="username")
input#inputUserEmail(type="text", placeholder="useremail", name="useremail")
button#btnSubmit(type="submit") submit

I tried to explain everything in a short way. I will try to upload and video to show you everything.

Run your project and go to these two address to see your result:

http://localhot:3000/userlist

http://localhot:3000/adduser

Bye bye



Categories: mongodb, Node.Js

Tags: ,

3 replies

  1. Thanks for sharing your article and i refer it, i liked it and refer below link for more information:http://www.s4techno.com/blog/category/mongodb/

Trackbacks

  1. How can connect to the MongoDB through Node.js? | Dinesh Ram Kali.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: