Search This Blog

Tuesday 7 March 2017

Mongodb Not connecting in Node js


Step 1
Install mongo db using following command

npm install mongodb --save
Step 2

Create the following folder C:\data\db

step 3

  • cd to C:\Program Files\MongoDB\Server\3.2\bin
  • enter command mongod
  • by default, mongodb server will start at port 27017Mongodb not connecting in nodejs                     


setp 4 
Write following code and run nodejs application using visual studio IDE


var MongoClient = require('mongodb').MongoClient;

// Connect to the db
MongoClient.connect("mongodb://localhost:27017/MyDb", function (err, db) {
   
     if(err) throw err;

     //Write databse Insert/Update/Query code here..
                
});
  
step 5
 
perform Insert operation using below code
 
var MongoClient = require('mongodb').MongoClient;

// Connect to the db
MongoClient.connect("mongodb://localhost:27017/db", function (err, db) {
    db.collection('TestData', function (err, collection) {
    collection.insert({ id: 1, firstName: 'Test', lastName: 'Test11' });
    collection.insert({ id: 2, firstName: 'Test1', lastName: 'Test12' });
    collection.insert({ id: 3, firstName: 'Test2', lastName: 'Test21' });
    db.collection('TestData').count(function (err, count) {
            if (err) throw err;

            console.log('Total Rows: ' + count);
        });
    });

}); 
 
 
 
 
 
 
 

5 comments: