【发布时间】:2017-04-17 15:46:35
【问题描述】:
我正在使用 koa v2 和 pg-promise。我尝试在参数化/准备语句中做一个简单的SELECT 2 + 2; 来测试我的设置:
// http://127.0.0.1:3000/sql/2
router.get('/sql/:id', async (ctx) => {
await db.any({
name: 'addition',
text: 'SELECT 2 + 2;',
})
.then((data) => {
console.log('DATA:', data);
ctx.state = { title: data }; // => I want to return num 4 instead of [Object Object]
})
.catch((error) => {
console.log('ERROR:', error);
ctx.body = '::DATABASE CONNECTION ERROR::';
})
.finally(pgp.end);
await ctx.render('index');
});
在模板中呈现[Object Object] 并将其从pg-monitor 返回到控制台:
17:30:54 connect(postgres@postgres)
17:30:54 name="addition", text="SELECT 2 + 2;"
17:30:54 disconnect(postgres@postgres)
DATA: [ anonymous { '?column?': 4 } ]
我的问题:
我想将结果4 存储在ctx.state 中。不知道如何在[ anonymous { '?column?': 4 } ]内访问?
感谢您的帮助!
编辑:
我在官方 wiki 中找到了另一个 recommended(1) ways(2) 来处理命名参数。
// http://127.0.0.1:3000/sql/2
router.get('/sql/:id', async (ctx) => {
const obj = {
id: parseInt(ctx.params.id, 10),
};
await db.result('SELECT ${id} + ${id}', obj)
.then((data) => {
console.log('DATA:', data.rows[0]['?column?']);
ctx.state = { title: data.rows[0]['?column?'] }; // => 4
})
.catch((error) => {
console.log('ERROR:', error);
ctx.body = '::DATABASE CONNECTION ERROR::';
})
.finally(pgp.end);
await ctx.render('index');
});
我将any 对象更改为result,它返回原始文本。比我访问号码4 像一个javascript 对象。难道我做错了什么?还有其他方法可以访问此值吗?
推荐的、更快速、更安全的使用方法是什么?
【问题讨论】:
标签: javascript sql node.js koa pg-promise