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

问题描述 投票:6回答:2

我用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(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
2个回答
6
投票

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

1
投票

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

将model属性设置为:

{
  type: 'Point',
  coordinates: [ lat, long ],
  crs: { type: 'name', properties: { name: 'EPSG:4326'} }
}
© www.soinside.com 2019 - 2024. All rights reserved.