插入不匹配列名的对象

Insert objects without matching column name

这可能是一个愚蠢的问题,但我是 node 和 postgresql 的新手,所以我很挣扎。

我正在尝试使用 pgp.helpers.insert 将多个对象插入数据库,如下例所示:

users = [{mycolumn:{name: 'John', age:23}}, {mycolumn:{name: 'Mike', age: 30}}];
query = pgp.helpers.insert(users, ['mycolumn:json'], 'mytable');
// insert into "mytable"("mycolumn") values('{"name":"John","age":23}'),('{"name":"Mike","age":30}')

上面的代码将 mytable 2 行插入 mycolumn 作为 jsonb。

但我试图直接插入 mycolumn 对象数组中的值,而不包装我的原始对象,例如:

users = [{name: 'John', age:23}, {name: 'Mike', age: 30}];
query = pgp.helpers.insert(users, ['mycolumn:json'], 'mytable');
// Error: Property 'mycolumn' doesn't exist.

当然不行,因为对象不包含 mycolumn 属性。但我认为在我的数组中迭代用列名包装原始对象并不优雅,特别是因为我正在处理数百万行(当然是分批处理)。

提前致谢。

您可以根据 Column 语法为您的列使用以下定义:

{
  name: 'mycolumn',
  init: c => c.source // use the source object itself
}

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

然后使用它:

const query = pgp.helpers.insert(users, cs);

请注意,我们没有指定修饰符 - mod: ':json',因为我们从 init 返回一个对象,默认情况下对象的格式为 JSON。