Monday, June 2, 2014

Connect MongoDB with nodeJS


In following example will explain the how to make connection nodeJS with mongodb.
  • create directory connectdb
  • first create package.json file inside the connectdb directory and add following content. then cd to connectdb directory and install dependancy by using npm install command
  • {
    "name": "cars",
    "description": "cars application",
    "version": "0.0.1",
    "private": true,
    "dependencies": {
    "express": "3.x",
    "mongodb": "1.1.8"
    },
    "engines": {
    "node": "0.8.4",
    "npm": "1.1.49"
    }
    }
    view raw package.json hosted with ❤ by GitHub
  • In this file contains dependency modules. 
  • cd to connectdb directory and enter following command then dependency modules will be installed 
       npm install 
  • Then create server.js/ app.js file.To run nodejs application run this server.js file. This is the entry point for the application.
var express = require('express'),
path = require('path'),
http = require('http'),
car = require('./routes/cars');
var app = express();
app.configure(function () {
app.set('port', process.env.PORT || 3000);
app.use(express.logger('dev')); /* 'default', 'short', 'tiny', 'dev' */
app.use(express.bodyParser()),
app.use(express.static(path.join(__dirname, 'public')));
});
app.get('/cars', car.findAll);
app.get('/cars/:id', car.findById);
app.delete('/cars/:id', car.deleteCar);
http.createServer(app).listen(app.get('port'), function () {
console.log("Express server listening on port " + app.get('port'));
});
view raw server.js hosted with ❤ by GitHub

Create car module
Create routes/cars.js file. This contains car related code.
 
var mongo = require('mongodb');
var Server = mongo.Server,
Db = mongo.Db,
BSON = mongo.BSONPure;
console.log("top");
var server = new Server('localhost', 27017, {auto_reconnect: true});
db = new Db('cardb', server, {safe: true});
db.open(function(err, db) {
if(!err) {
console.log("Connected to 'cardb' database");
db.collection('cars', {safe:true}, function(err, collection) {
if (err) {
console.log("The 'cars' collection doesn't exist. Creating it with sample data...");
populateDB();
}
});
}
});
exports.findById = function(req, res) {
var id = req.params.id;
console.log('Retrieving car: ' + id);
db.collection('cars', function(err, collection) {
collection.findOne({'_id':new BSON.ObjectID(id)}, function(err, item) {
res.send(item);
});
});
};
exports.findAll = function(req, res) {
db.collection('cars', function(err, collection) {
collection.find().toArray(function(err, items) {
res.send(items);
});
});
};
exports.deleteCar = function(req, res) {
var id = req.params.id;
console.log('Deleting car: ' + id);
db.collection('cars', function(err, collection) {
collection.remove({'_id':new BSON.ObjectID(id)}, {safe:true}, function(err, result) {
if (err) {
res.send({'error':'An error has occurred - ' + err});
} else {
console.log('' + result + ' document(s) deleted');
res.send(req.body);
}
});
});
}
/*--------------------------------------------------------------------------------------------------------------------*/
// Populate database with sample data -- Only used once: the first time the application is started.
// You'd typically not find this code in a real-life app, since the database would already exist.
var populateDB = function() {
var cars = [
{
name: "vitz",
year: "2009",
brand: "toyota",
country: "Japan",
region: "asia",
description: "toyota Vitz car",
picture: "saint_cosme.jpg"
},
{
name: "priuse",
year: "2009",
brand: "toyota",
country: "Japan",
region: "asia",
description: "toyota Priuse car",
picture: "viticcio.jpg"
},
{
name: "city",
year: "2009",
brand: "honda",
country: "Japan",
region: "asia",
description: "honda city car",
picture: "ex_umbris.jpg"
}];
db.collection('cars', function(err, collection) {
collection.insert(cars, {safe:true}, function(err, result) {});
});
};
view raw car.js hosted with ❤ by GitHub
You can get code from following link
 https://github.com/cchathura/cmeanstack.git/branches/connectdb