Skip to content

Instantly share code, notes, and snippets.

@Ouwen
Last active May 3, 2019 18:56
Show Gist options
  • Star 10 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Ouwen/f29ac508b2965101833f to your computer and use it in GitHub Desktop.
Save Ouwen/f29ac508b2965101833f to your computer and use it in GitHub Desktop.
Using PostGIS with sequelize
'use strict';
var Q = require('q');
module.exports = function (sequelize, DataTypes) {
return sequelize.define('Snapshot', {
time: {
type: DataTypes.DATE
}
}, {
instanceMethods: {
setGeoJson: function (geojson) {
var deferred = Q.defer();
sequelize.query('UPDATE "public"."Snapshots" SET geom= ST_GeomFromGeoJSON(\'' + geojson + '\') WHERE id=' + this.id).then(function (result) {
deferred.resolve(result);
}).catch(function (err) {
deferred.reject(err);
});
return deferred;
},
getGeoJson: function () {
var deferred = Q.defer();
sequelize.query('SELECT ST_AsGeoJSON(geom, 15, 2) FROM "public"."Snapshots" WHERE id =' + this.id).then(function (result) {
deferred.resolve(result);
}).catch(function (err) {
deferred.reject(err);
});
return deferred;
}
}
});
};
// In your DB Start Config file
sequelize.sync({
force: true
}).then(function () {
// Add the geometry column
sequelize.query('SELECT AddGeometryColumn(\'public\',\'Snapshots\',\'geom\',\'0\',\'MULTIPOLYGON\',2);').then(function () {
console.log('DEV: Postgres Database is synced.');
// Populate DB with sample data
if (config.database.seedDB) {
require('./seed');
}
}).catch(function (err) {
console.log('DEV: Error adding geometry column');
});
}).catch(function (err) {
console.log('DEV: Postgres Database is not synced.', err);
});
@flockonus
Copy link

line 40 should seems to be missing return ?

@aphillipo
Copy link

aphillipo commented Jul 17, 2018

Probably worth using parameters here to avoid SQL insertion should this be anywhere near user inputted data, for example:

sequelize.query(
    'UPDATE "public"."Snapshots" SET geom=ST_GeomFromGeoJSON(?) WHERE id=?',
    { replacements: [geoJson, this.id],  type: sequelize.QueryTypes.UPDATE }
)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment