栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

使用pg-promise跳过更新列

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

使用pg-promise跳过更新列

我是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。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/485065.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号