Saturday 22 August 2015

REST Service with mongoose



In this example we will expose REST service on top of MongoDB with Node.js using mongoose.Please see my previous blog post for getting started.

Please open the 'app.js' file and do the following modification.
We will remove the saving of the data we did in our previous example and will insert code snippet which will add a REST service on top of the schema we added earlier.
 It is as easy as below :
app.get('/mongooseexample', function (req, res) {
    Employee.find({},function(err,users){
        if (err) return console.error(err);
       
      res.send(users);
  })
});


Please find the complete app.js here

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

/
//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');
    }
 
});
// REST service to fetch Employee data

app.get('/mongooseexample', function (req, res) {
    Employee.find({},function(err,users){
        if (err) return console.error(err);
      
      res.send(users);
  })
});

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 open your favorite browse and call http://localhost:3000/mongooseexample. You will see the result as below ( off course your MongoDB should be up and running )

 

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)