You need to enable JavaScript to run this app. 使用promisify封装Postgres查询判断值存在返回对象而非布尔的问题
优惠活动
大模型
产品
解决方案
定价
更多

使用promisify封装Postgres查询判断值存在返回对象而非布尔的问题

问题排查与解决方案

根因说明

你使用的pg库(node-postgres)的查询方法返回值为标准的查询结果结构体,不会直接返回查询语句得到的字段值,你需要的布尔判断结果存储在返回对象的rows数组中。
从你打印的返回结果也能看到rows属性下已经存在[{"it_does_exist":false}]的返回内容,直接提取对应字段即可。

修正后的代码

const util = require('util')
const { Client } = require('pg');

const db = new Client({
  connectionString: process.env.DATABASE_URL,
  ssl: {
    rejectUnauthorized: false
  }
});

db.connect();

const queryP = util.promisify(db.query)

async function doStuff() {
  // 先获取查询结果对象
  const queryResult = await queryP.call(db, 'SELECT EXISTS(SELECT 1 FROM searchtable WHERE val = $1) AS it_does_exist', [testValue]);
  // 提取第一条记录的it_does_exist字段,即为所需布尔值
  const inDatabase = queryResult.rows[0].it_does_exist;
  console.log("In the Database: " + inDatabase);
}

内容的提问来源于stack exchange,提问作者nickcoding2

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.21 09:24:05