pg-promise是一个Node.js的PostgreSQL数据库接口库,它提供了一种方便的方式来连接和操作PostgreSQL数据库。它支持将查询结果以JSON格式输出,并且可以将外键封装为对象。
使用pg-promise格式化JSON输出的步骤如下:
npm install pg-promise
const pgp = require('pg-promise')();
const db = pgp('postgres://username:password@host:port/database');
其中,username
是数据库用户名,password
是数据库密码,host
是数据库主机名,port
是数据库端口号,database
是要连接的数据库名称。
db.any('SELECT * FROM table')
.then(data => {
const jsonOutput = JSON.stringify(data);
console.log(jsonOutput);
})
.catch(error => {
console.error(error);
});
在上述代码中,db.any()
方法执行了一个查询,并返回查询结果。然后,使用JSON.stringify()
方法将结果转换为JSON字符串,并输出到控制台。
db.any('SELECT t1.*, t2.name AS foreign_key_name FROM table1 t1 JOIN table2 t2 ON t1.foreign_key = t2.id')
.then(data => {
const jsonOutput = JSON.stringify(data);
console.log(jsonOutput);
})
.catch(error => {
console.error(error);
});
在上述代码中,使用JOIN语句将table1
和table2
连接起来,并将table2
中的name
字段作为外键对象的属性返回。
关于pg-promise的更多详细信息和用法,请参考腾讯云的pg-promise产品介绍。
领取专属 10元无门槛券
手把手带您无忧上云