2016-02-08 39 views
1
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 to connect to the 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); 


    }); 
} 

這是我正在使用的示例代碼,它在執行下面的代碼時拋出錯誤。任何人都可以請解釋爲什麼會發生?TypeError:無法讀取未定義的屬性'collection'這裏有什麼錯誤?

我得到的錯誤:

TypeError: Cannot read property 'collection' of undefined at exports.findAll (/home/android/student/pro1/route/connect1.js:16:6)
at callbacks (/home/android/student/pro1/node_modules/express/lib/router/index.js:164:37) at param (/home/android/student/pro1/node_modules/express/lib/router/index.js:138:11) at pass (/home/android/student/pro1/node_modules/express/lib/router/index.js:145:5) at Router._dispatch (/home/android/student/pro1/node_modules/express/lib/router/index.js:173:5) at Object.router (/home/android/student/pro1/node_modules/express/lib/router/index.js:33:10) at next (/home/android/student/pro1/node_modules/express/node_modules/connect/lib/proto.js:174:15) at Object.expressInit [as handle] (/home/android/student/pro1/node_modules/express/lib/middleware.js:30:5) at next (/home/android/student/pro1/node_modules/express/node_modules/connect/lib/proto.js:174:15) at 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 to port 8081'); 

回答

0

試試這個

// 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 to connect to the 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); 
     }); 
    } 

和你的主文件

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 to port 8081'); 
+0

我認爲這是不好的做法,通過該數據庫在一個共同的中間件你不覺得嗎? –

相關問題