【问题标题】:Insert objects without matching column name插入不匹配列名的对象
【发布时间】:2017-12-12 16:34:54
【问题描述】:

这可能是一个愚蠢的问题,但我是 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 属性。但是我认为在我的数组中迭代并用列名包装原始对象并不优雅,特别是因为我正在处理数百万行(当然是分批工作)。

提前致谢。

【问题讨论】:

    标签: javascript pg-promise


    【解决方案1】:

    您可以根据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。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-08-01
      • 2023-03-23
      • 1970-01-01
      • 2012-09-14
      • 1970-01-01
      • 2020-09-15
      • 1970-01-01
      相关资源
      最近更新 更多