CRUD using Node.js,Express.js,MongoDB

I try to explain CRUD operation Using Node.js ,Express.js and MongoDB

Installing Node.js

Go to http://nodejs.org, and click the Install button.
Run the installer that you just downloaded. When the installer completes, a message indicates that Node was installed at C:/program file/node/bin/node and npm was installed at C:/program file/node/bin/npm.
3.open editor save as app.js

var http = require(‘http’);

http.createServer(function (request, responce) {
responce.writeHead(200, { ‘Context-Type’: ‘text/plain’ });
responce.end(‘Hello World \n’);
}).listen(8080);
console.log(‘Server is running on port no 8080’);

4.Open command line.

eg. path>node app.js

5. in cmd console print like this Server is running on port no 8080

6.Open browser type in url – http://localhost:8080

7.Hello World print in browse window.

8. install express package like path>npm install express

9.modify app.js
var express = require(‘express’),

var app = express();

app.configure(function(){
app.use(express.logger(‘dev’));
app.use(express.bodyParser());
});

app.listen(8080);

console.log(‘Server is running on port 8080…’);

10.Now that Express is installed application running, we can stub a basic REST API for the CRUD application

11.Open app.js and replace its content as follows:

var express = require(‘express’),

products = require(‘./routes/products’);

var app = express();
app.configure(function(){
app.use(express.static(__dirname + ‘/View’));
app.use(express.logger(‘dev’));
app.use(express.bodyParser());
});

app.get(‘/’, function(req, res){
res.sendfile(__dirname + ‘/index.html’);
});
app.get(‘/products/:PName’, products.findByName);
app.post(‘/products/:PName/:Type/:Description’,products.addProduct);
app.put(‘/products/:PName/:Type/:Description’, products.updateProduct);
app.delete(‘/products/:PName’, products.deleteProduct);

app.listen(8080);
console.log(‘Server is running on port 8080…’);

12. create product modules in route directory /route/product.js

In product.js we will perfrom CRUD operation.

Install MongoDB.

1.To install MongoDB on your specific platform, refer to the MongoDB QuickStart. Here are some quick steps to install MongoDB on a window:
Open a terminal window and type the following command to download the latest release:
curl http://downloads.mongodb.org/osx/mongodb-osx-x86_64-2.2.0.tgz > ~/Downloads/mongo.tgz

Note: You may need to adjust the version number. 2.2.0 is the latest production version at the time of this writing.

Extract the files from the mongo.tgz archive:
cd ~/Downloads
tar -zxvf mongo.tgz

Move the mongo folder to /usr/local (or another folder according to your personal preferences):
sudo mv -n mongodb-osx-x86_64-2.2.0/ /usr/local/

(Optional) Create a symbolic link to make it easier to access:
sudo ln -s /usr/local/mongodb-osx-x86_64-2.2.0 /usr/local/mongodb

Create a folder for MongoDB’s data and set the appropriate permissions:
sudo mkdir -p /data/db
sudo chown `id -u` /data/db

Start mongodb
cd /usr/local/mongodb
./bin/mongod

You can also open the MongoDB Interactive Shell in another terminal window to interact with your database using a command line interface.
cd /usr/local/mongodb
./bin/mongo

Refer to the MondoDB doc.

To provide the data access logic for each route, modify Product.js as follows

var express = require(‘express’);
var mongo = require(‘mongodb’);
var Server = mongo.Server,
Db = mongo.Db,
BSON = mongo.BSONPure;

var server = new Server(‘localhost’, 27017, { auto_reconnect: true });
db = new Db(‘productsDB’, server);

//Open Connection
db.open(function (err, db) {
if (!err) {
console.log(“Connected to ‘productsDB’ database”);
db.collection(‘products’, { strict: true }, function (err, collection) {
if (err) {
console.log(“The ‘productsDB’ collection doesn’t exist. Creating it with sample data…”);
// populateDB();
}
});
}

Write all CRUD operation in Product.js.

exports.findByName = function (req, res) {
var PName = req.params.name;
db.collection(‘products’, function (err, collection) {
collection.find({ “PName”: PName }).toArray(function (err, names) {
res.header(“Content-Type:”, “application/json”);
res.send(JSON.stringify(names));
}); // End Collection.find()
}); //End db.collection()
}; //End findByName

exports.addProduct = function (req, res) {
var product = req.body;
db.collection(‘products’, function (err, collection) {
collection.insert(product, { safe: true }, function (err, result) {
if (err) {
res.send({ ‘error’: ‘An error has occurred’ });
} else {
console.log(‘Success: ‘ + JSON.stringify(result[0]));
res.send(“Successfully Add product”);
console.log(“Add Record”);
}
});
});
}

exports.updateProduct = function (req, res) {
var product = req.body;
db.collection(‘products’, function (err, collection) {
collection.update({ PName: req.params.PName }, { PName: req.params.PName, Type: req.params.Type, Description: req.params.Description });
console.log(“Record is Update”);
res.send(req.body);
});
}

exports.deleteProduct = function (req, res) {
var PName = req.params.PName;
console.log(‘Deleting product: ‘ + PName);
db.collection(‘products’, function (err, collection) {
collection.remove({ PName: PName });
res.send(req.body);
});
}

});

Enjoy…..

Advertisements

2 thoughts on “CRUD using Node.js,Express.js,MongoDB

  1. Pretty portion of content. I just stumbled upon your blog and in accession capital to claim that I get actually loved account your weblog
    posts. Anyway I’ll be subscribing to your feeds or even I fulfillment you get
    admission to consistently fast.

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