【发布时间】:2017-03-04 05:24:48
【问题描述】:
我编写了一个简单的 express.js 服务器来处理 REST API 请求并从 MongoDB 数据库中获取数据。当我向特定端点(“localhost:8081/api/getUserData”)发出 GET 请求时,promise 链无法按我想要的方式工作,我仍然不明白。
这是我得到的错误: "[TypeError: Cannot read property 'db' of undefined]"
var MongoClient = require('mongodb').MongoClient;
var express = require('express');
var app = express();
var rp = require("request-promise");
var cors = require('cors');
// use it before all route definitions
app.use(cors({ origin: '*' }));
/********************** REST API FUNCTIONS **********************/
app.get('/api/getUserData', function (req, res, next) {
var context = {};
console.log("in api getUserData")
context.db_url = 'mongodb://localhost:27017/test';
openDatabaseConnection(context)
.then(getAllUserLocations)
.then(closeDatabaseConnection)
.then(function (context) {
res.send(context.userLocations)
})
.catch(function (error) {
console.log("ERROR :");
console.log(error);
})
})
/********************** END REST API FUNCTIONS **********************/
function getAllUserLocations(context) {
context.db.collection("test").find().toArray().then(function (err, result) {
console.log("Received from db: " + result.length + " objects");
context.userLocations = result;
return context;
});
}
function openDatabaseConnection(context) {
console.log("Opening DB connection...");
return MongoClient.connect(context.db_url)
.then(function (db) {
console.log("DB connection opened.");
context.db = db;
return context;
})
}
function closeDatabaseConnection(context) {
console.log("Closing DB connection");
return context.db.close()
.then(function () {
console.log("DB connection closed");
return context;
})
}
/********************** STARTING SERVER **********************/
var server = app.listen(8081, function () {
var host = server.address().address
var port = server.address().port
console.log("Githex server listening at http://%s:%s", host, port)
})
任何帮助都将不胜感激,甚至更多的解释,因为我不明白我做错了什么。
谢谢!
【问题讨论】:
-
由于
context被定义为只有db_url属性的对象,当您在getAllUserLocations函数中使用它时,它没有db属性 -
不幸的是,事实并非如此。我从代码中删除了我提供的另一个有效的 api 请求处理程序,但没有指定“db”属性。我只是尝试在承诺链之前添加一个 db 属性,但它也没有解决它..
-
你是对的,错误表明
context在你的一个函数中是未定义的,它不能"read property 'db' of undefined",它可能带有行号和更具体的位置信息。 -
例如,
getAllUserLocations()并没有真正返回任何东西,它必须是return context.db.collection(...假设函数也返回一个承诺。 -
是的,我添加了“return context.db”等,解决了这个问题,但现在又出现了一个^^,我现在会尝试解决那个问题。非常感谢!
标签: javascript mongodb rest api express