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

How to separate controller and database queries for Node and pg-promise

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

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

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;
    }
  );
}

在路线文件夹中,我有一条名为 "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" 以在 table 中显示 "db.locationList"。

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

我不想将控制器层与数据库层混为一谈,但如何解决这个问题?

我认为你应该把你的 db/location.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
      });
  });
  ...

在你的例子中console.log(db.locationList);在数据可用之前运行,因为它是异步的。它的工作方式与您期望的不同。