簡體   English   中英

如何為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,它可以查詢位置表。

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”,以便在表中顯示“ 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); 在數據可用之前運行,因為它是異步的。 它不能像您期望的那樣工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM