Last active
May 28, 2024 03:42
-
-
Save Ouwen/f29ac508b2965101833f to your computer and use it in GitHub Desktop.
Using PostGIS with sequelize
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'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); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Probably worth using parameters here to avoid SQL insertion should this be anywhere near user inputted data, for example: