在使用 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'});
第一个 source
是 pg-promise
API 支持的内容,第二个是您的数据列名称:)
此外,根据documentation ,API 将 source
和 this
设置为相同,因此如果您更喜欢 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/