【问题标题】:Insert/Update PostGis Geometry with Sequelize ORM使用 Sequelize ORM 插入/更新 PostGis 几何
【发布时间】:2018-05-27 11:11:24
【问题描述】:

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

有谁知道挂钩到 Sequelize 以便将 srid 添加到发送到 PostGis 的 GeoJson 的方法?放在哪里?在模型的二传手中?

【问题讨论】:

    标签: sequelize.js postgis geojson


    【解决方案1】:

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

    设置模型属性为:

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

    【讨论】:

      【解决方案2】:

      似乎 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'
                }
              };
            }
          }
        }
      });
      

      【讨论】:

      • 谢谢@mcranston18,这就是我要找的。正如你所说,不理想,但我会使用它:)
      • 我已经尝试过了,但并不高兴。 beforeSave (sequelize v4.20) 没有被调用 - 我已经在其中放置了一个从未显示的 console.log。我不能在这里发布代码,但它看起来或多或少和你的一样。有什么想法吗?
      • 现在发布新问题,代码:stackoverflow.com/questions/48358408/…
      猜你喜欢
      • 2020-09-25
      • 2015-11-10
      • 2020-12-21
      • 2019-07-03
      • 1970-01-01
      • 2021-05-04
      • 1970-01-01
      • 2020-03-21
      • 2019-08-23
      相关资源
      最近更新 更多