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

How can Install MongoDB and Create Database?

Hey Guys,

Now it is time to do some fantastic thing, normally connecting to database and retrieving data from database or writing into database is quite interesting if you are working with new platform and tools. Today I want to show you how to connect to the MongoDB and retrieve data (of course I will teach you how to insert first), for a few seconds forget about node.js and focus on MongoDB, in order to create a database in MongoDB we need to follow the below steps:

  1. MongoDB is an open source database which can be downloaded from the: http://www.mongodb.org . So please open the link and download it. For this tutorial we need MongoDB version Windows 64-bit 2008 R2+
  2. If you cannot do it please close the website and turn off your pc and do something else as you are not qualified for developing. (Just kidding) if you have difficulty to download or install, please click here to see the video which I uploaded on my YouTube channel.
  3. After you install, you need to run your MongoDB server, it is very easy.
    1. Please make sure that you created Data folder in your node folder, I created something like this : E:\node\nodetest1\data
    2. Now we want to create database and copy necessarily files into the data folder. Open command prompt and go to the MongoDB bin folder, (if you watch video you can see how I moved to bin folder). For those lazy people that do not want watch video you can find Bin folder in this address:

C:\MongoDB\Server\3.0\bin

After you moved to this folder key in the below command:

mongod –dbpath E:\node\notetest1\data

Note:  dbpath is the address of data folder, so maybe your data folder address is different from mine, please change it accordingly.

Note: In some cases I saw that mongod does not work, so for this case you need to key in the full address of mongod.exe, actually mongod is exe file in bin folder!!!!

Note: it may take a few seconds to a few minutes for command to be finished so please be patient.

  1. After you ran the command you could see a few files and folders are created in Data folder and also in your command prompt window you can see MongoDB is waiting for connection.
  2. It means you are in a right direction and your MongoDB is waiting for connection.
  3. Something like this:
  4. Be default mongoDB is connected to the test database and even you can see the name of test on your screen once you copy all the necessarily  files to the data folder, but do not worry about it, we can always switch to our own database, for this purpose you need to run the MondoShell, to run MondoShell you need to run the below command:

C:\MongoDB\Bin\mongo.exe

After you press enter you can see something like this:

MongoDB Wating for connection

To change the database you can type this command:

Use [name of you database]

Connect to Differtent Database

Mongo DB uses Json data structure to keep data, so before we go further I want to show you how Json format looks like:

{“name”:”Mehran”,”code”:”123”}

{“name”:”Arash”,”code”:”234VF”}

{“name”:”Arman”,”code”:”EDRng”}

Basically json format is very simple and understandable for human.

How can we add record to our database?

In order to add records to your database you can use the below command:

db.insert.testcollection.insert({“name”:”Arman”,”code”:”EDRng”})

In the above command, testcollection is a user defined name for the collection. It means you can change it as you want. This collection looks like and array and keep all the records. Above command must be ran in mongo shell. (Same as step 5).

How can we retrieve records?

In order to retrieve data you can run the below command:

db.testcollection.find ().pretty ()

Then result is something like this:

{

“_id” : ObjectId(“55d1b2028f5be420d8a167fc”),

“name” : “Mehran”,

“code” : “123”

}

MongoDB use

in the next post I will teach you how to retrieve data from MongoDb and show it Html file by using Node.js.

bye bye 🙂