如何在Node.js的Sequelize中获取不含CRS的PostGIS Geometry列
如何用Sequelize获取不含CRS的PostGIS Geometry数据
以下是三种可行的解决方案,按需选择:
方法1:数据库查询层面生成不带CRS的GeoJSON
利用PostGIS的ST_AsGeoJSON函数,通过控制参数排除CRS信息。在Sequelize中结合sequelize.literal实现:
const results = await YourModel.findAll({ attributes: [ 'id', // 生成不带CRS的GeoJSON字符串,指定坐标精度为6 [sequelize.literal('ST_AsGeoJSON(location, 6, false)'), 'location'] ], raw: true }); // 将GeoJSON字符串转为JS对象 const processedData = results.map(item => ({ ...item, location: JSON.parse(item.location) }));
ST_AsGeoJSON的第三个参数includeCRS设为false,即可跳过CRS对象的生成,第二个参数用于设置坐标小数精度。
方法2:在模型定义中添加自定义Getter
在Sequelize模型里给location字段定义getter,自动过滤CRS属性:
const YourModel = sequelize.define('YourModel', { // 其他字段定义 location: { type: DataTypes.GEOMETRY('POINT', 4326), get() { const rawVal = this.getDataValue('location'); if (rawVal?.crs) { return { type: rawVal.type, coordinates: rawVal.coordinates }; } return rawVal; } } });
后续查询返回的模型实例,location字段会自动剔除CRS部分,直接返回目标结构。
方法3:查询结果后手动处理
如果不想修改模型或查询逻辑,可在获取数据后遍历处理:
const instances = await YourModel.findAll(); const processedData = instances.map(instance => { const data = instance.toJSON(); if (data.location?.crs) { data.location = { type: data.location.type, coordinates: data.location.coordinates }; } return data; });
内容的提问来源于stack exchange,提问作者AAhsan siddiqui
相关产品推荐
相关产品推荐

