在将节点中的logging保存到nodejs中的postgres之前,异议js模型字段数据修剪

我正在使用objection.js ORM为我的node.js项目。 一切都很好,我想在实际保存PostGres数据库表中的数据之前修剪所有的字段。 我也在一些项目中使用mongoose,它允许在模型中定义{trim:true}。

我正在为参考添加一个示例模型代码:

// @flow import Model from './Model'; import Transaction from './Transaction'; import dbMap from './dbMap'; export default class ClaimCode extends Model { amount: number; claimId: number; code: string; codeDate: Date; presentOnAdmission: string; throughDate: Date; claimCodeTypeId: number; static tableName = 'claim_code'; } dbMap(ClaimCode, {}); 

我们有没有办法在异议JS模型中做同样的事情?

我认为你应该能够创build基础模型并覆盖$formatDatabaseJson(json)方法,它可以遍历所有string字段并在保存前修剪它们( http://vincit.github.io/objection.js/#_s_formatdatabasejson ) 。

 class YourBaseModel extends Model { $formatDatabaseJson(json) { json = super.$formatDatabaseJson(json); // trim here all strings too before returning json... return json; } } 

如果您希望在从HTTP请求中读取数据等模型创build时修改值,重写$parseJson()可能会更好。