使用 Sequelize ORM 插入/更新 PostGis 几何图形

2023-12-30

我使用sequelize-auto提取了一些PostGis图层的模型,给出:

module.exports = function(sequelize, DataTypes) {
return sequelize.define('table', {
  id: {
    type: DataTypes.INTEGER,
    allowNull: false,
    primaryKey: true,
    autoIncrement: true
  },
  geom: {
    type: DataTypes.GEOMETRY('POINT', 4326),
    allowNull: true,
  },
...

在 GET Sequelize 上,将 geom 作为 GeoJSON 发送到客户端:

{
  "type":"Point",
  "coordinates":[11.92164103734465,57.67219297300486]
}

当我尝试使用以下命令保存此回 PostGis 错误时:

ERROR:  Geometry SRID (0) does not match column SRID (4326)

这个答案给出了如何添加 SRID 的神指示(如何在 Sequelize ORM 中插入 PostGIS GEOMETRY 点? https://stackoverflow.com/questions/32059758/how-to-insert-a-postgis-geometry-point-in-sequelize-orm),

var point = { 
  type: 'Point', 
  coordinates: [39.807222,-76.984722],
  crs: { type: 'name', properties: { name: 'EPSG:4326'} }
};

User.create({username: 'username', geometry: point }).then(function(newUser) {
...
});

据我所知,SRID 曾经是一个从sequelize 中删除的功能(https://github.com/sequelize/sequelize/issues/4054 https://github.com/sequelize/sequelize/issues/4054).

有谁知道如何连接 Sequelize 以便将 srid 添加到发送到 PostGis 的 GeoJson 中?放在哪里?在模型的设置器中?


看来 Sequelize 在保存时不会保存 SRIDGEOMETRY字段(请注意,它正确地将 SRID 保存在GEOGRAPHY场地)。那么当您以后更新该模型时,更新将会失败,因为它没有在该模型上设置 SRIDGEOMETRY模型定义中预期的字段。

这不是一个理想的解决方案,但您可以使用 Sequelize 的beforeSave挂钩始终指定要使用的坐标系。

myDatabase.define('user', {
  name: {
    type: Sequelize.STRING
  },
  geometry: {
    type: Sequelize.GEOMETRY('POINT', 4326)
  }
}, {
  hooks: {
    beforeSave: function(instance) {
      if (instance.geometry && !instance.geometry.crs) {
        instance.geometry.crs = {
          type: 'name',
          properties: {
            name: 'EPSG:4326'
          }
        };
      }
    }
  }
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 Sequelize ORM 插入/更新 PostGis 几何图形 的相关文章

随机推荐