Sequelize Model where value is set using a PostgreSQL/PostGIS function

eczajk Source

Is it possible to set up a Sequelize model in such a way that an instance is written to the database using a PostgreSQL (or PostGIS, in my case) function?

My database leverages PostGIS, and I would like for the value for "the_geom" to be written as a function of the latitude and longitude:

var Site = sequelize.define('site', {
  the_geom: 'geometry(Point,4326)',
  latitude: DataTypes.DECIMAL,
  longitude: DataTypes.DECIMAL
});

The value for the_geom would typically be something like this:

ST_SetSRID(ST_MakePoint(-76.622,39.277),4326)
postgresqlpostgissequelize.js

Answers

answered 2 years ago eczajk #1

I was able to achieve my desired result using hooks:

var Site = sequelize.define('site', {
        the_geom: 'geometry(Point,4326)',
        latitude: DataTypes.DECIMAL,
        longitude: DataTypes.DECIMAL
}, {
  hooks: {
      afterValidate: function (site, options) {
        site.the_geom = sequelize.fn('ST_SetSRID', sequelize.fn('ST_MakePoint', site.longitude, site.latitude), '4326');
      }
    }
  });

comments powered by Disqus