这可能是个愚蠢的问题,但我是 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 .
关于javascript - 插入不匹配列名的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47724641/