Friday, 28 April 2017

How to get MongoDB Collection information from a Get request

I am trying to return collection data from my get request

I have done this

const express = require('express');
const app = express();

app.listen(3000, function() {
  console.log('listening on 3000')
})

      var MongoClient = require('mongodb').MongoClient
  , assert = require('assert');

// Connection URL
var url = 'mongodb://localhost:27017/EmployeeDB';
// Use connect method to connect to the Server
MongoClient.connect(url, function(err, db) {
  assert.equal(null, err);
  console.log("Connected correctly to server");

  db.close();
});


app.get('/', function (req, res){
     db.open(function(err,db){ // <------everything wrapped inside this function
         db.collection('Employee', function(err, collection) {
             collection.find().toArray(function(err, items) {
                 console.log(items);
                 res.send(items);
             });
         });
     });
});

When i run the above program i get

ReferenceError: db is not defined
    at D:\Express Project\smart3d.js:23:6
    at Layer.handle [as handle_request] (D:\Express Project\node_modules\express\lib\router\layer.js:95:5)
    at next (D:\Express Project\node_modules\express\lib\router\route.js:137:13)
    at Route.dispatch (D:\Express Project\node_modules\express\lib\router\route.js:112:3)
    at Layer.handle [as handle_request] (D:\Express Project\node_modules\express\lib\router\layer.js:95:5)
    at D:\Express Project\node_modules\express\lib\router\index.js:281:22
    at Function.process_params (D:\Express Project\node_modules\express\lib\router\index.js:335:12)
    at next (D:\Express Project\node_modules\express\lib\router\index.js:275:10)
    at expressInit (D:\Express Project\node_modules\express\lib\middleware\init.js:40:5)
    at Layer.handle [as handle_request] (D:\Express Project\node_modules\express\lib\router\layer.js:95:5)

Could you please tell me how to resolve this .



via Pawan

No comments:

Post a Comment