Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link

commented Mar 15, 2017

line 40 should seems to be missing return ?

@aphillipo

This comment has been minimized.

Copy link

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
You can’t perform that action at this time.