Saturday 15 August 2015

Getting started with MongoDB and Node.js mongoose


Creating REST service on top of MongoDB is becoming common. Recently I needed to do a POC regarding the same and found mongoose is really handy.Please go through below to learn a quick startup.We will start with set up and connection to MongoDB in this article.


Pre - requisite :
You need to have the below mentioned software installed in your system and off course connected to internet. 
  • MongoDB 3x
  • Node.js ( Latest version available , I have used v0.12.7 for this example)
Now lets move to a directory where you want to create the Node server and create the following empty file :
  1. package.json
  2. app.js
Paste the below code in package.json file.
{
  "name": "mongoose_example",  
  "main": "app.js", 
  "author": "Sumit",
  "dependencies": {
   
    "express": "latest",
    "express-stormpath": "latest",   
    "mongoose": "latest"   
  }
}


Execute the commd from your directory. It will install the necessary files.



 Now lets build our express server. Paste the code mentioned below in app.js file and save it.

var express = require('express');
var app = express();
var mongoose = require('mongoose');
var db = mongoose.connection;

// Define a schema
var Schema = mongoose.Schema;
var empSchema = new Schema({
                                name : String,
                                empid : Number,
                                DOB : Date,
                                isActive : Boolean
                                });

// bind schema with model
var Employee = mongoose.model('Employee', empSchema);

// initilize
var empdata = new Employee({
                                name : 'Sumit',
                                age : 1234,
                                DOB : '01/01/2007',
                                isActive : true
                                });
//connect to mongoDB
mongoose.connect('mongodb://localhost/mongooseexample',function (err, res) {
    if (err) {
        console.log ('ERROR connecting to:' + err);
    } else {
    console.log ('Succeeded connected to:  mongodb://localhost/mongooseexample');
    }
 
});
// save the employee data to DB
empdata.save();

var server = app.listen(3000, function () {
  var host = server.address().address;
  var port = server.address().port;

  console.log('Example app listening at http://%s:%s', host, port);
});

Now start the express server. If there is no error in your console , you have saved an employee record in your MongoDB.



Lets check the data in MongoDB. Open a mongo shell and issue the following commands. You will find one employee record. Please note that the collection name stored in MongoDB is 'employees' ( mind the extra 's' ).
 
 

In the next session  we will show an example of REST service to fetch record from MongoDB.


No comments:

Post a Comment