Node / Express & Postgresql - 当没有行匹配时

Node / Express & Postgresql - when no rows match

你好,我是 Postgresql 的新手,我想了解如何在抛出错误时处理 0 个结果。本质上我想得到一个用户,如果它不存在, return null 如果不存在,并且有一个错误处理程序。以下是我正在使用的当前代码。任何关于更好的方法的提示都将不胜感激!

var options = {
  // Initialization Options
  promiseLib: promise
};
var pgp = require('pg-promise')(options);
var connectionString = 'postgres://localhost:5432/myDbName';
var db = pgp(connectionString);

function getUser(id) {         
  let user = new Promise(function(resolve, reject) {
    try {
      db.one('select * from users where loginName = ', id).then(function(data) {
        console.log(data);
        resolve(data); 
      }).catch (function (e) {
        console.log('error: '+e);
        reject(e);
      });
    }
    catch (e) {
      console.log('error: '+e);
      reject(e);
    }
  });
  return user;
}

控制台输出:

error: QueryResultError {
    code: queryResultErrorCode.noData
    message: "No data returned from the query."
    received: 0
    query: "select * from users where loginName = 'someUserName'"
}

在查询的捕获处理程序中,只需测试该错误。查看pg-promise源代码,noData的代码为0。所以就这样做:

db.one('select * from users where loginName = ', id).then(function(data) {
        console.log(data);
        resolve(data); 
      }).catch (function (e) {
        if(e.code === 0){
          resolve(null);
        }
        console.log('error: '+e);
        reject(e);
      });

我是 pg-promise 的作者。


在 promises 领域中,使用 .then 来处理所有正常情况,使用 .catch 来处理所有错误情况。

翻译成 pg-promise,它遵守该规则,您执行一个数据库方法,该方法解析为代表所有正常情况的结果,因此其他任何结果都在 .catch.[=22 中=]

举个例子,如果返回一行或不返回行是您查询的正常情况,您应该使用方法 oneOrNone. It is only when returning no row is an invalid situation you would use method one

根据 API,方法 oneOrNone 使用找到的数据行进行解析,或者当没有找到行时使用 null 进行解析,然后您可以检查:

db.oneOrNone('select * from users where loginName = ', id)
    .then(user=> {
        if (user) {
            // user found
        } else {
            // user not found
        }
    })
    .catch(error=> {
        // something went wrong;     
    });

但是,如果您有一个没有返回数据的查询确实代表错误,检查是否没有返回行的正确方法应该是这样的:

var QRE = pgp.errors.QueryResultError;
var qrec = pgp.errors.queryResultErrorCode;

db.one('select * from users where loginName = ', id)
    .then(user=> {
        // normal situation;
    })
    .catch(error=> {
        if (error instanceof QRE && error.code === qrec.noData) {
            // found no row
        } else {
            // something else is wrong;
        }
    });

选择方法时也有类似的考虑 many vs manyOrNone (method any is a shorter alias for manyOrNone).

类型 QueryResultError 有一个非常友好的控制台输出,就像库中的所有其他类型一样,让您很好地了解如何处理这种情况。