我是pg-promise的作者;)
var pgp = require('pg-promise')({ capSQL: true // capitalize all generated SQL});// generic way to skip NULL/undefined values for strings:function str(col) { return { name: col, skip: function () { var val = this[col]; return val === null || val === undefined; } };}// generic way to skip NULL/undefined values for integers,// while parsing the type correctly:function int(col) { return { name: col, skip: function () { var val = this[col]; return val === null || val === undefined; }, init: function () { return parseInt(this[col]); } };}// Creating a reusable ColumnSet for all updates:var csGeneric = new pgp.helpers.ColumnSet([ str('string1'), str('string2'), str('string3'), str('string4'), str('string5'), str('string6'), int('integer1'), int('integer2'), int('integer3'), str('date1'), str('date2'), str('date3')], {table: 'generic1'});// Your new request handler:function updateRecord(req, res, next) { var update = pgp.helpers.update(req.body, csGeneric) + ' WHERe id = ' + parseInt(req.params.id); db.none(update) .then(function () { res.status(200) .json({ 'status': 'success', 'message': 'updated one record' }); }) .catch(function (err) { return next(err); });}参见helpers名称空间;)
另外,您可以对每列进行自己的验证,然后相应地生成
UPDATE查询,尽管它不会那么优雅;)
更新
请注意,在库的版本5.4.0中,方式
init和
skip参数化已更改,请参见发行说明。
从5.4.0版开始,您可以简化代码,如下所示:
// generic way to skip NULL/undefined values for strings:function str(column) { return { name: column, skip: c => c.value === null || c.value === undefined };}// generic way to skip NULL/undefined values for integers,// while parsing the type correctly:function int(column) { return { name: column, skip: c => c.value === null || c.value === undefined, init: c => +c.value };}而且,如果您要跳过根本没有传入的属性,因此甚至不存在于对象中,请使用以下方法:
skip: c => c.value === null || c.value === undefined
你可以这样做:
skip: c => !c.exists
更新
库的5.6.7版本对此选项进行了进一步改进
emptyUpdate,当指定此选项时,该选项表示方法要返回的值,而不是throwing
Cannotgenerate an UPDATE without anycolumns。有关详细信息,请参见helpers.update。
另请参见:ColumnConfig。



