2

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)

1 Answer 1

3

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');
      }
    }
  });
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.