Category: nodejs

How to Insert dynamic data using Node.js, Express.js, Angular.js and MongoDB?

First, we have to install and configure NodeJS and mongoDB.
Installing NodeJs on windows:
Install it from :
Confirm that Node is running correctly:
Here are some steps to make sure that Node is running correctly.
⦁    Create helloNode.js file
var http=require(‘htttp’);
res.end(“Hello world”);
console.log(‘server is running on port:3000’);
⦁    Run it through command prompt.
 F:\sonika\config\node helloNode.js
        server is running on port:3000
⦁    Open browser and type URL: http://localhost:3000/
⦁    The output will be:
Hello world
⦁    Now,your node is running correctly.
Configuring  MongoDB :
⦁    Download zip file  from this link:
⦁    Unzip it and Put it in particular directory.
⦁    Create ‘data\db’ folders in that directory to store our data(we can give any name to that folder).
⦁    Go to that directory’s lib folder and run it  for that go through following command.
⦁    F:\Sonika\All Data\software\mongodb\bin>mongod.exe  –dbpath  F:\Sonika\All     Data\software\mongodb\data\db    
⦁    Press ‘Enter’.

⦁ It will look like this,


⦁    Now,your MongoDB is ready to store data.
Now, lets develop an Student Registration form sample application
For that, we have to follow some steps:-
⦁    Create directory structure.

⦁    Create package.json file.
This text file contains all the information about the project,
like project path,dependencies, author name, tags, bug tracking info  etc..
To create a package.json run npm init command from the root folder.
It will ask series of questions and finally
it will create package.json file.
Our package.json file will look like this.

⦁    Create ‘index.html’ file.
This html file will create UI that have two manus “HOME”  and “ADD DETAILS”.
⦁    Create ‘add.html’ file.
    Note: Don’t write <html> and <body> tag in ‘add.html’ and ‘Home.html’ files
because, these files are partialy render inside <ng-view> tag that defined

in index.html file.
⦁    Create’ Home.html’ file.
<h2>Welcome !</h2>
<h4>Exam Registration Site!</h4>
⦁    Create ‘styles.css’ file.
This file describe code to design UI.
    Create  ‘appModule.js’  file.
Angular follow MVC pattern that is Model,View,Controller.
This is a Model part of our application that will describe business logic.Our model           name is “myapp” that is already define in index.html file.
If we changed model part then View part will definatly reflect.
‘use strict’;
angular.module(‘myapp’, []).
config([‘$routeProvider’, ‘$locationProvider’,

function($routeProvider, $locationProvider) {
$routeProvider.when(‘/add’, {templateUrl: ‘partials/add.html’, controller: AppCtrl});
$routeProvider.when(‘/home’, {templateUrl: ‘partials/Home.html’});
$routeProvider.otherwise({redirectTo: ‘/’});

⦁    Create ‘controllers.js’ file 
This is our controller part that will manage flow of executation.
In this file, we described controller “AppCtrl” that is already define in  ‘index.html’ file.
‘use strict’;
function AppCtrl($scope,$http,$location) {
$scope.form = {};
alert(‘Thank you…!’);

AppCtrl.$inject = [‘$scope’,’$http’,’$location’];  //here we inject dependancies

⦁    Create ‘CRUDOper.js’ file.
In this file we described all database configuration like server,database name,

collection name  as well as logic of insertion of data into mongoDB.
⦁    Create ‘app.js’ file.
This file described configuration of express server as well as create instance of

directories that we will use further in our Application and serve static file      i.e“index.html”.
⦁    Now,our Application is ready.
⦁    To run our Application.First we have to run “package.json” file.
⦁    when we will run this file through command prompt then all dependancies and packages  that are describe in “package.json” file will install and that all required to run our application.
⦁    Now,open command prompt and go in root directory of Application i.e  ‘AngularJsApp’.
⦁    Run F:\sonika\Data\AngularJsApp> npm install
⦁    Now, run  ‘app.js’ file to start our express server.
⦁    Run command ‘node app.js’
⦁    Open browser and type URL: http://localhost:3000/
If we click on  ‘Home’ then ‘Home.html’ will render.
If we click on ‘ADD DETAILS’ then ‘add.html’ file will render.
Fill out information in the form and submit to check if application is working fine.
To check our filled data  in MongoDB we have to follow some steps:
⦁    Open second command prompt.
⦁    Go in lib directory of MongoDB and run ‘mongo.exe’.
⦁    mongo.exe will open.
⦁    Type  ‘show databases’  then we will see our database name  ‘studb’.
⦁    Type  ‘use studb’  that is it will use our database to perform operations.
⦁    Type show collections then it will show  our collections name that is ‘students’.
⦁    To see our filled data type  ‘db.students.find()’ .
⦁    Note: Our database name ‘studb’ and collection name ‘students’  are already define in   ‘CRUDOper.js’  file.
⦁    It will look like this,

“Download complete source code from”:
Have fun..!

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, 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. 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’);
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();



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.use(express.static(__dirname + ‘/View’));

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

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 > ~/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

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

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 (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 =;
db.collection(‘products’, function (err, collection) {
collection.find({ “PName”: PName }).toArray(function (err, names) {
res.header(“Content-Type:”, “application/json”);
}); // 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”);

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 });