node.js - TypeError: Cannot read property 'collection' of undefined what is the mistake here? -


var mongodb = require('mongodb'); var mongoclient = mongodb.mongoclient; var url = 'mongodb://localhost:27017/projectone'; var db1=mongoclient.connect(url, function (err, db) {   if (err) {     console.log('unable connect mongodb server. error:', err);   } if(!err) {      console.log('connection established to', url);  } }); exports.findall = function(req, res)  { var collection = db1.collection('student');    collection.find().toarray(function (err, result) {       res.send(result);       }); } 

this sample code working , throwing error on executing below code. please explain why happens?

the error got:

typeerror: cannot read property 'collection' of undefined @ exports.findall (/home/android/student/pro1/route/connect1.js:16:6)
@ callbacks (/home/android/student/pro1/node_modules/express/lib/router/index.js:164:37) @ param (/home/android/student/pro1/node_modules/express/lib/router/index.js:138:11) @ pass (/home/android/student/pro1/node_modules/express/lib/router/index.js:145:5) @ router._dispatch (/home/android/student/pro1/node_modules/express/lib/router/index.js:173:5) @ object.router (/home/android/student/pro1/node_modules/express/lib/router/index.js:33:10) @ next (/home/android/student/pro1/node_modules/express/node_modules/connect/lib/proto.js:174:15) @ object.expressinit [as handle] (/home/android/student/pro1/node_modules/express/lib/middleware.js:30:5) @ next (/home/android/student/pro1/node_modules/express/node_modules/connect/lib/proto.js:174:15) @ object.query [as handle] (/home/android/student/pro1/node_modules/express/node_modules/connect/lib/middleware/query.js:43:5)

var express=require('express'), connect=require('./route/connect3');  var app=express();  app.get('/con',connect.findall); app.listen(8081); console.log('listening port 8081'); 

try this

// connect3.js var mongodb = require('mongodb'); var mongoclient = mongodb.mongoclient; var url = 'mongodb://localhost:27017/projectone';  module.exports = mongoclient.connect(url, function (err, db) {   if (err) {         console.log('unable connect mongodb server. error:', err);   } if(!err) {         console.log('connection established to', url);         return db;     } });  exports.findall = function(req, res) {     var collection = req.db.collection('student');         collection.find().toarray(function (err, result) {             res.send(result);         });     } 

and main file

var express=require('express'), const db = require('./route/connect3'); var app = express(); app.use(function(req, res, next) {     req.db = db;     next(); })    app.get('/con',connect.findall); app.listen(8081); console.log('listening port 8081'); 

Comments

Popular posts from this blog

javascript - jQuery: Add class depending on URL in the best way -

caching - How to check if a url path exists in the service worker cache -

Redirect to a HTTPS version using .htaccess -