node.js - 使用 pg-promise 将 ColumnSet 列转换为几何
问题描述
我正在使用 pg-promise 创建一个ColumnSet对象,根据这个:
const cs = new pgp.helpers.ColumnSet([
{name: 'Id',prop: 'Id'},
{name: 'Lat',prop: 'Lat'},
{name: 'Lng',prop: 'Lng'},
{name: 'CreationDateTime',prop: 'CreationDateTime'},
{name: 'Topic',prop: 'Topic'},
{name: 'UserId',prop: 'UserId'},
{name: 'shape',mod: ':raw',prop: 'shape',def: 'point'},
{name: 'UserName',prop: 'UserName'},
{name: 'appName',prop: 'appName'},
{name: 'appVersion',prop: 'appVersion'}
], {
table: 'Location'
});
def: 'point'
点是转换为几何的方法——这是一个值,或者我如何运行点方法并在此列(形状)中进行绑定?
并为批量插入编写此方法:
async function insertMany(values) {
try {
let results = await db.none(pgp.helpers.insert(values, cs));
} catch (error) {
console.log(error);
}
}
为了转换 lat 和 lng 我写了这个方法:
const point = (lat, lng) => ({
toPostgres: () => pgp.as.format('ST_SetSRID(ST_MakePoint($1, $2), 4326)', [Lag, Lng]),
rawType: true
});
但我得到了这个错误:
TypeError: Values null/undefined cannot be used as raw text
根据此页面:
原始文本变量以 :raw 或符号 ^ 结尾,并防止文本转义。此类变量不允许为 null 或 undefined,否则方法会抛出 TypeError = Values null/undefined cannot be used as raw text。
当不执行点方法时,该形状字段当然为空。
解决方案
首先,您正在滥用 option prop
,该选项被记录为在目标属性名称与列名称不同时使用,这不是您的情况。
并且def
,正如还记录的那样,表示缺少属性时的值。当该属性设置为null
or时,不使用undefined
的值。def
您正在尝试覆盖结果值,这意味着您需要使用 property init
。
point
另一个问题 - 您在实现切换案例中的变量。
总之,您的代码应如下所示:
const getPoint = col => {
const p = col.value;
// we assume that when not null, the property is an object of {lat, lng},
// otherwise we will insert NULL.
return p ? pgp.as.format('ST_SetSRID(ST_MakePoint(${lat}, ${lng}), 4326)', p) : 'NULL';
};
const cs = new pgp.helpers.ColumnSet([
'Id',
'Lat',
'Lng',
'CreationDateTime',
'Topic',
'UserId',
{name: 'shape', mod: ':raw', init: getPoint},
'UserName',
'appName',
'appVersion',
], {
table: 'Location'
});
使用自定义类型格式的版本如下所示:
const getPoint = col => {
const p = col.value;
if(p) {
return {
toPostgres: () => pgp.as.format('ST_SetSRID(ST_MakePoint(${lat}, ${lng}), 4326)', p),
rawType: true
};
}
// otherwise, we return nothing, which will result into NULL automatically
};
const cs = new pgp.helpers.ColumnSet([
'Id',
'Lat',
'Lng',
'CreationDateTime',
'Topic',
'UserId',
{name: 'shape', init: getPoint},
'UserName',
'appName',
'appVersion',
], {
table: 'Location'
});
推荐阅读
- python - Python 与 Maya 选择对象并旋转它
- python - 使用 groupby 和 count 对列表进行排序
- javascript - 是否可以流式输入一个返回另一个可能被柯里化的函数的函数?
- r - 聚类的不确定性
- capybara - 如何使用 Capybara Rails 5.2 测试 React Dropzone
- javascript - 在 React 组件中动态设置 props
- node.js - 通过node js访问USB iPhone 8 plus上的照片
- python - 在画布内创建框架?
- sql - SQL 动态表插入 SQL Server
- java - 带有 CA 签名证书的 2 路 TLS