Foreign Key Naming in Sequelize and Postgres
Sequelize is a pretty nice ORM wrapper for Node.js. It keeps focus on writing JavaScript and helps avoid the annoying mental context-switch to SQL. And even though it's a somewhat leaky abstraction it makes a programmer more productive. And in this century, who doesn't like being more productive, huh?
Now, speaking about leaky abstractions, there's one syntactic issue that bothers me when mapping PostreSQL to JavaScript via Sequelize. You see, the prevalent naming convention in Postgres is to use underscores for column names. But the standard in JS is to use camelCase. This brings along a minor annoyance when defining column names; fortunately there's the underscored
flag that automagically converts camelCased fields to underscored and/or - if you're not into magic that much - the field
option that allows defining the column names explicitly.
So that's all wonderful and peachy. But what about foreign keys? In Sequelize one usually defines them via belongsTo
- or similar methods - like so:
const User = sequelize.define('user', {
firstName: {
type: Sequelize.STRING,
field: 'first_name'
},
lastName: {
type: Sequelize.STRING,
field: 'last_name'
}
}, {
freezeTableName: true,
// Little bit of healthy paranoia.
underscored: true
});
const Group = sequelize.define('group', {
name: {
type: Sequelize.STRING
}
}, {
freezeTableName: true,
// Little bit of healthy paranoia.
underscored: true
});
User.belongsTo(Group)
This would generate a group_id
column on the user
table. Which is good postgres-wise, however, if you create a new user object, the JS representation will have a group_id
field instead of groupId
.
Using name
option
Fortunately, there's a simple solution - it's a bit more verbose but also nicely explicit. We can use the name
option of the foreignKey
mapping.
Like so:
User.belongsTo(Group, {foreignKey: {
name: 'groupId',
field: 'group_id'
}});
When defined this way, the created user JS object will have a camelCased groupId
foreign key field while the column name in postgres will stay underscored (group_id
). There you go.
Do you know a better way? I'm @tomas_brambora!