使用 Sequelize ORM 插入/更新 PostGis 几何 [英] Insert/Update PostGis Geometry with Sequelize ORM
问题描述
我用 sequelize-auto 提取了一些 PostGis 层的模型,给出:
I have extracted models of some PostGis layers with sequelize-auto, giving:
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 发送到客户端:
On GET sequelize sends the geom to the client as GeoJSON:
{
"type":"Point",
"coordinates":[11.92164103734465,57.67219297300486]
}
当我尝试通过以下方式保存这个 PosGis 错误时:
When I try to save this back PosGis errors with:
ERROR: Geometry SRID (0) does not match column SRID (4326)
这个答案很好地说明了如何添加 SRID (如何在 Sequelize ORM 中插入 PostGIS GEOMETRY 点?),
This answer gives a god indication of how to add the 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).
I understand that SRID used to be a feature that was removed from sequelize (https://github.com/sequelize/sequelize/issues/4054).
有谁知道挂钩到 Sequelize 以便将 srid 添加到发送到 PostGis 的 GeoJson 的方法?放在哪里?在模型的二传手中?
Does anyone know a way to hook into Sequelize so that the srid is added to the GeoJson sent to PostGis? Where to put it? In a setter on the model?
推荐答案
似乎 Sequelize 在保存 GEOMETRY
字段时没有保存 SRID(注意,它正确地将 SRID 保存在 <代码>地理代码>字段).然后,当您将来更新该模型时,更新将失败,因为它没有按照模型定义中的预期在 GEOMETRY
字段上设置 SRID.
It seems that Sequelize does not save the SRID when saving a GEOMETRY
field (note, that it correctly saves the SRID on a GEOGRAPHY
field). Then when you update that model in the future, the update will fail because it does not have a SRID set on the GEOMETRY
field as expected in the model definition.
这不是一个理想的解决方案,但您可以使用 Sequelize 的 beforeSave
挂钩来始终指定要使用的坐标系.
This isn't a desirable solution, but you can use Sequelize's beforeSave
hook to always speciify the coordinates system to use.
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'
}
};
}
}
}
});
这篇关于使用 Sequelize ORM 插入/更新 PostGis 几何的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!