【发布时间】:2018-03-16 14:12:06
【问题描述】:
我从pg-promise documentation 观察到这个代码示例:
const obj = {
one: 1,
two: 2
};
db.query('INSERT INTO table(${this:name}) VALUES(${this:csv})', obj);
//=> INSERT INTO table("one","two") VALUES(1, 2)
我正在尝试做类似的事情,这是一个 MWE:
var insertObj = {rating_text: 'Example goes here!',
pros: 'Example pro',
cons: 'Example con',
stars: '5',
product_id: '20',
account_id: '1'}
var insertObj['rating_date'] = Date.now()
console.log(insertObj)
console.log(pgp.as.format('INSERT INTO product_rating(${this:name}) VALUES(${this:csv})', insertObj))
db.none('INSERT INTO product_rating(${this:name}) VALUES(${this:csv})', insertObj)
我使用pgp.as.format 来查看传递给postgres 的SQL。上面的输出是这样的:
{rating_text: 'Example goes here!',
pros: 'Example pro',
cons: 'Example con',
stars: '5',
product_id: '20',
account_id: '1',
rating_date: 1520886741488}
INSERT INTO product_rating("rating_text",
"pros",
"cons",
"stars",
"product_id",
"account_id",
"rating_date") VALUES('{"rating_text":"Example goes here!",
"pros" :"Example pro",
"cons" :"Example con",
"stars" :"5",
"product_id" :"20",
"account_id" :"1",
"rating_date":1520886741488}')
为了便于阅读,我对 SQL 进行了格式化。
此 SQL 显然不起作用,因为整个对象作为单个字符串提供并返回错误:
UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 2): error: INSERT has more target columns than expressions
我希望 VALUES() 的格式与文档中的一样。
为什么文档示例在我的 MWE 中不起作用?是不是因为db.query -> db.none 函数交换?
【问题讨论】:
标签: javascript node.js pg-promise