如何分离 Node 和 pg-promise 的控制器和数据库查询



我正在编写一个Web应用程序,使用NodeJS,express和pg-promise来显示来自PostgreSQL数据库内容的网页。

我有一个名为"db/location.js"的数据库javascript,它查询位置表。

var db_global = require('./db');  # db.js is for building the database connection
var db = db_global.db;
var locationList = [];
// add query functions
module.exports = {      
getAllLocationList: getAllLocationList,
locationList: locationList
};
function getAllLocationList() {
db.any('select * from location')
.then(function (data) {
console.log(data);
locationList = data;
}
);
}

在 routes 文件夹中,我有一个名为"locationRoute.js"的路由 javascript。

var express = require('express');
var router = express.Router();
var db = require('../db/location');
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
/* GET the map page */
router.get('/locations', function(req, res) {
db.getAllLocationList();
console.log(db.locationList);
res.render('locations', {
title: "Express and Leaflet API", // Give a title to our page
//jsonData: db.getAllLocations // Pass data to the View
jsonData: db.locationList // Pass data to the View
});
});
module.exports = router;

当调用"http://localhost:3000/locations"时,这应该呈现"locations.jade",即在表中显示"db.locationList"。

我的问题是"console.log(db.locationList(;"总是在查询完成之前被调用。这导致"db.locationList"(jsonData(为空。

我不想将控制器层与数据库层弄乱,但是如何解决问题?

我认为您应该更改您的数据库/位置.js像这样...

function getAllLocationList() {
return db.any('select * from location');
}

然后你会在你的路线中做这样的事情......

router.get('/locations', function(req, res) {
db.getAllLocationList()
.then(function(data) {
res.render('locations', {
title: "Express and Leaflet API", // Give a title to our page
jsonData: data // Pass data to the View
});
});
...

在示例控制台中.log(db.locationList(; 在数据可用之前运行,因为它是异步的。它没有按照您期望的方式工作。

最新更新