node.js - 从 ColumnSet 访问源对象

标签 node.js pg-promise

在使用 ColumnSet 中列的 initCB 属性导入数据时,我尝试拆分记录集中的子对象。

但是当我对两个不同的目标名称但一个源使用两个不同的初始化函数时,我得到相同的结果。

const cs = new pgp.helpers.ColumnSet([
  'id',
  { name: 'source_id', prop: 'source', init: function(obj) { return obj.value.id; } },
  { name: 'source_name', prop: 'source', init: function(obj) { return obj.value.name; } },
], { table: 'test_table' });

const data = [
  { id: 1, source: { id: 1, name: 'source1' } },
  { id: 2, source: { id: 1, name: 'source1' } },
  { id: 3, source: { id: 2, name: 'source2' } },
];

const insert = pgp.helpers.insert(data, cs);

结果是:

INSERT INTO "test_table"("id","source_id","source_name") VALUES
  (1,'source1','source1'),
  (2,'source1','source1'),
  (3,'source2','source2')

而不是预期:

INSERT INTO "test_table"("id","source_id","source_name") VALUES
  (1,1,'source1'),
  (2,1,'source1'),
  (3,2,'source2')

这似乎是对同一源字段的回调函数的第二次调用覆盖了之前在此源字段上调用另一个回调函数的结果。

如何避免这种情况? 或者还有另一种在导入过程中分割子对象的方法?

最佳答案

选项 prop 不太适合这种方式。它用于将重新映射到不同的属性名称,但它不提供直接对象引用。

相反,请使用 column descriptor 的属性 source ,引用源对象。讽刺的是,您也在数据 source 中调用了该属性,这意味着您必须在引用中使用 source 两次:

const cs = new pgp.helpers.ColumnSet([
    'id',
    {name: 'source_id', init: c => c.source.source.id},
    {name: 'source_name', init: c => c.source.source.name}
], {table: 'test_table'});

第一个 sourcepg-promise API 支持的内容,第二个是您的数据列名称:)

此外,根据documentation ,API 将 sourcethis 设置为相同,因此如果您更喜欢 ES5 函数语法(对于您的示例来说看起来更清晰),那么您可以这样做:

const cs = new pgp.helpers.ColumnSet([
    'id',
    { name: 'source_id', init: function() {return this.source.id;}},
    { name: 'source_name', init: function() {return this.source.name;}},
], { table: 'test_table' });

上面我们有 this 指向源数据对象。

关于node.js - 从 ColumnSet 访问源对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56662738/

相关文章:

javascript - 类型错误 : Invalid connection Details (PG-Promise)

javascript - 如何根据登录动态分配 Express.js 中的数据库路径?

javascript - "Converting circular structure to JSON"BigQuery 从云函数 NodeJs 插入

unit-testing - 如何用玩笑模拟 pg-promise 库

javascript - 如何使用 ES6 语法导入 pg-promise?

javascript - Pg-promise:链接条件查询

node.js - 如何使用 ejs 模板引擎仅渲染数据而不在 Node js 中重新加载整个页面

node.js - 一些连接术语

node.js - 如何确保多个租户的 SAML 安全?

postgresql - 带有 pg-promise 的复合类型