问题
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,
},
...
On GET sequelize sends the geom to the client as GeoJSON:
{
"type":"Point",
"coordinates":[11.92164103734465,57.67219297300486]
}
When I try to save this back PosGis errors with:
ERROR: Geometry SRID (0) does not match column SRID (4326)
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) {
...
});
I understand that SRID used to be a feature that was removed from sequelize (https://github.com/sequelize/sequelize/issues/4054).
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?
回答1:
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.
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'
}
};
}
}
}
});
回答2:
Declare the column type as: DataTypes.GEOMETRY('Point')
,
Set the model attribute as:
{
type: 'Point',
coordinates: [ lat, long ],
crs: { type: 'name', properties: { name: 'EPSG:4326'} }
}
来源:https://stackoverflow.com/questions/47795113/insert-update-postgis-geometry-with-sequelize-orm