How to define and use geo points in sequelize with mySQL

3.4k Views Asked by At

I'm using sequelize ORM to connect to a MYSQL database - how would I define a geo POINT in the table/object model? Since sequelize doesn't have a POINT data type can I just pass in a string that represents a MYSQL type?

db.define(modelName, {
    id: {
        type: Sequelize.INTEGER,
        primaryKey: true,
        autoIncrement: true,
        allowNull: false
    },
    location:{
        type:'POINT' //how would I define this??
    },
    createdBy: {
        type: Sequelize.INTEGER,
        references: {
            model: 'User',
            key: 'id'
        }
    },
    photoId: {
        type: Sequelize.UUID
    },
    caption: {
        type: Sequelize.STRING
    }
}
2

There are 2 best solutions below

3
On

You could create it through STRING and create a custom toJSON implementation on the instance so you can get a POINT you want.

Data Types Instance methods

On those instance methods you can define also a toJSON custom method which will be automatically called when sending the object through res.send(obj)

0
On

Since 3.4.0 Sequelize support geometry for postgres. Based on commit messages, MySQL is also supported.

You can add new attribute like this:

point: {
   type: Sequelize.GEOMETRY('POINT'),
},

The supported types for MySQL are:

var SUPPORTED_GEOMETRY_TYPES = ['POINT', 'LINESTRING', 'POLYGON'];