如何通过pg-promise传递表名和参数

我是新来的节点,随后pg-promise。 我正在尝试在我的节点快车应用程序中实现的是一个path,将作为一个API在数据库中的表中执行单个字段更新。 这只是一个单独的路由,将使用表名称,列名称,列值和列标识值来标识表中要更新的行。

这是我到目前为止所尝试的代码,但我似乎无法做到这一点:

router.post('/update_db_field', function (req, res, next) { db.one('update $table~ set $dbcol~=$dbcolval~ where $dbcolid~=$dbcolidval~ returning $colid~', [ req.body.table, req.body.dbcol, req.body.dbcolid, req.body.dbcolval, req.body.dbcolidval ]).then(function (data) { console.log(data) res.send(data) }).catch(function (error) { console.log("ERROR:", error.message || error); // print error; }); }) 

不幸的是,它抛出了以下错误:

ERROR: syntax error at or near "$"

是否还有一种方法来打印来自catch()函数的查询string,以便debugging可以更容易一些?

您将variables格式与命名参数混淆,您的查询应该是:

 router.post('/update_db_field', function (req, res, next) { db.one('UPDATE ${table~} SET ${dbcol~} = ${dbcolval} WHERE ${dbcolid~} = {dbcolidval} RETURNING ${colid~}', req.body, a => a[req.body.dbcolid]) .then(function (dbcolid) { console.log(dbcold) res.send(dbcolid) }) .catch(function (error) { console.log("ERROR:", error.message || error); // print error; }); }) 

虽然你仍然可能会遇到问题,因为传入一个dynamic的表+列意味着你不知道如何将它们转换为正确的types,所以举例来说,最终可能会将你的dbcolval作为string传入,而需要是一个整数,然后查询会因此而被拒绝。

请注意,我们添加了可选的a => a[req.body.dbcolid] ,所以不是用具有一个属性的对象parsing,而是直接使用属性值来parsing。

如何查看在控制台中打印的查询文本?

 var query = pgp.as.format(query, values); console.log(query); 

API: as.format 。