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 )

 

No comments:

Post a Comment