Insert/Update PostGis 几何与 Sequelize ORM

Insert/Update PostGis Geometry with Sequelize ORM

我已经使用 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]
}

当我尝试通过以下方式保存此 PosGis 错误时:

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

这个答案给出了如何添加 SRID () 的上帝指示,

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) 中删除的功能。

有谁知道连接到 Sequelize 以便将 srid 添加到发送到 PostGis 的 GeoJson 的方法?放在哪里?在setter模特上?

似乎 Sequelize 在保存 GEOMETRY 字段时不保存 SRID(请注意,它正确地将 SRID 保存在 GEOGRAPHY 字段上)。然后,当您将来更新该模型时,更新将失败,因为它没有像模型定义中预期的那样在 GEOMETRY 字段上设置 SRID。

这不是理想的解决方案,但您可以使用 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'
          }
        };
      }
    }
  }
});

将列类型声明为:DataTypes.GEOMETRY('Point')

将模型属性设置为:

{
  type: 'Point',
  coordinates: [ lat, long ],
  crs: { type: 'name', properties: { name: 'EPSG:4326'} }
}