gpt4 book ai didi

node.js - 类型错误 : Cannot read property 'collection' of undefined what is the mistake here?

转载 作者:太空宇宙 更新时间:2023-11-04 02:17:01 25 4
gpt4 key购买 nike

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

最佳答案

试试这个

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

关于node.js - 类型错误 : Cannot read property 'collection' of undefined what is the mistake here?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35266812/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com