【问题标题】:NodeJs - Rendering same page after multiple SELECT queriesNodeJs - 在多个 SELECT 查询后呈现同一页面
【发布时间】:2016-12-09 21:36:30
【问题描述】:

我的 index.js 文件中有以下代码。我可以打印配置文件表的数据。而且我还需要在同一(index.njk)页面中打印简历表的数据。但我做不到。我还找到了similar question,但我是新手,无法根据我的项目修改这些代码。你能帮忙吗?

var express = require('express'),
path = require('path'),
bodyParser = require('body-parser'),
router = express.Router(),
app = express();
var pg =require('pg');

// DB Connect string
var connect = {
user: 'arslan', 
database: 'resumedb', 
password: '1984',
host: 'localhost', 
port: 5432, 
max: 10, 
idleTimeoutMillis: 30000, 
};

router.get('/', function(req, res){
pg.connect(connect, function(err, client, done, skills){
  if(err){
    return console.error('errrr', err)
  }
  //Get Profile Informations
client.query('select id,fname,lname,title,description,profileimage from profile', function(err, result){

    if(err){
      return console.error('error running query', err);
    }
   if(result.rows.length > 0) {
          res.render('index.njk', { 
                profileName: result.rows[0].fname,
                profileLName: result.rows[0].lname , profileTitle: result.rows[0].title
              , profileDesc: result.rows[0].description 
              , profileImage: result.rows[0].profileimage
          });

       console.log(result.rows[0].profileimage);
    }else {
        console.log('No rows found in DB');
    }
    done() 
});
}); 
});

【问题讨论】:

  • 查看pg-promise,这是构建依赖和独立查询的最简单方法;)

标签: node.js postgresql express nunjucks


【解决方案1】:

所有异步内容的最佳解决方案是使用 Promises。 您的代码将配置用于连接池,但后来您不使用池,但使用它通常是一个好主意。 您创建一个新模块db.js 来查询数据库

const pg = require('pg')

const connect = { // Normaly you would use an config file to store this information
  user: 'arslan',
  database: 'resumedb',
  password: '1984',
  host: 'localhost',
  port: 5432,
  max: 10,
  idleTimeoutMillis: 30000
}

let pool = new pg.Pool(config)

exports.query = (query, values) => {
  return new Promise((resolve, reject) => {
    pool.connect(function(err, client, done) {
      if (err)
        return reject(err)
      client.query(query, values, (err, result) => {
        done()
        if (err)
          return reject(err)
        resolve(result)
      })
    })
  })
}

exports.queryOne = (query, values) => {
  return new Promise((resolve, reject) => {
    this.query(query, values).then(rows => {
      if (rows.length === 1) {
        resolve(rows[0])
      } else if (rows.length === 0) {
        resolve()
      } else {
        reject(new Error('More than one row in queryOne'))
      }
    }).catch(err => {
      reject(err)
    })
  })
}

pool.on('error', function (err, client) {
  console.error('idle client error', err.message, err.stack)
})

然后在你的路线中

// ...
const db = require('./db')

router.get('/', function(req, res, next) {

  let profileQuery = db.queryOne('select id,fname,lname,title,description,profileimage from profile')
  let resumeQuery = db.query('???')
  Promise.all([profileQuery, resumeQuery]).then(([profile, resume]) => {
    if (!profile) {
        return res.status(404).send('Profile not found') // error page
    res.render('index.njk', { 
            profileName: profile.fname,
            profileLName: profile.lname,
            profileTitle: profile.title,
            profileDesc: profile.description,
            profileImage: profile.profileimage
      })
  }).catch(err => {
    next(err)
  })

})

如果您想进行单个查询,可以使用db.query('select 1 + 1').then(rows => { /* your code */}).catch(err => { next(err) })。 因为您通常只想要一行,所以可以使用queryOne。它返回 undefined 没有行、您想要的行或多行错误

以错误为参数的next() 将调用快速错误处理程序。在那里您可以记录错误并返回 500。您应该为此创建自己的

如果有不明白的地方请询问,因为第一次可能会很复杂:)

【讨论】:

  • 你的代码真的很复杂 :) 我需要很多时间来处理它,如果可行,请打勾。感谢您的建议。
  • 嗨@Julian,我无法使用此代码。我使用了link 答案的逻辑。我在回答中分享我的代码。他们工作正常,但我需要找到一种更好的方式连接到 PostgreSql。因为我的网页在第二次点击后卡住了。您能否查看我的代码以帮助我了解连接?
  • 为什么不能用?在您的代码中,查询一个接一个地执行,而不是同时执行,但是如果您不需要更快的响应时间,那没关系。第二次调用的错误是什么(使用if (err) { console.log(err) } 或更好的错误处理程序和next,就像我在回答中描述的那样)。可能是您的错误是将代码混合用于单个连接和连接池。看看这里github.com/brianc/node-postgres 的示例,对于您使用 client.end 而不是 done 的单个连接
  • 我是新手,因为它需要时间来理解 :) 。在所有页面完成后,我将在稍后再次优化期间处理您的代码。但是现在,通过在link 页面中使用 Pool,它现在可以正常工作了。我将继续按照这个逻辑完成项目。非常感谢您的帮助。
猜你喜欢
  • 1970-01-01
  • 2021-01-15
  • 2023-04-09
  • 2021-10-13
  • 1970-01-01
  • 2010-10-13
  • 1970-01-01
  • 2011-09-20
  • 2021-08-26
相关资源
最近更新 更多