【发布时间】:2017-11-28 16:09:52
【问题描述】:
我正在尝试从我的流星 mongo 数据库中获取信息并将其显示为我的网页上的 json,但我收到错误 TypeError: Cannot read property 'find' of undefined,我不知道为什么。
var MongoClient = require('mongodb').MongoClient;
var db;
// Initialize connection once
MongoClient.connect("mongodb://localhost:3001", function(err, database) {
if(err) //console.log(err);
console.log(database);
db = database;
// Start the application after the database connection is ready
app.listen(3001);
console.log("Listening on port 3000");
});
// middleware to use for all requests
router.use(function (req, res, next) {
// do logging
//console.log('Something is happening.');
next(); // make sure we go to the next routes and don't stop here
});
router.route('/subscribers')
app.get("/api/subscribers", function (req, res) {
db.subs.find({}, function(err, docs) {
docs.each(function(err, doc) {
if(doc) {
res.json(doc);
}
else {
res.end();
}
});
});
});
【问题讨论】:
-
检查您的数据库是否已连接,因为您的 app.port ant DB 端口正在同一端口上运行
-
根据文档,您应该在
db对象上调用collection方法来访问集合。即db.collection('subs').find(...) -
感谢@AhmadBaktashHayeri 是问题所在^^
标签: javascript json node.js mongodb