Sequelize & Node JS ORMs in 2021

Since 2020 took a serious hit on the excitement in my life, I thought I’d start out 2021 on a high-note: taking Sequelize, a Node JS ORM, for a spin 🚗.

A woman in blue looking at a large map outdoors in front of a white car
A woman in blue looking at a large map outdoors in front of a white car
Photo by Leah Kelley from Pexels

What is an ORM?

An ORM, short for Object Relational Mapper, is a tool that allows us to (in this case) interact with the database of our program in our preferred programming language.

Think of it as Google Translate between you and your database: it takes in commands in one language and maps them to another - allowing you to create, read, update and delete data without having to “speak” the databases’ language¹.

If you’ve dealt with projects that required storing lots of organized information, you’ve likely encountered code written in Structured Query Language (SQL). SQL is a domain-specific language that allows you to manage data held in relational database management systems², such as PostgreSQL. You may have even written something like this:

// Select all names and phone numbers of hotels located in Sydney
SELECT name, phone_number
FROM hotels
WHERE city = 'Sydney';

While SQL is a powerful language, some find the syntax to be awkward and error-prone. ORMs in their ideal form abstract some of the logic from database operations, resulting in fewer lines of code and a more efficient work-flow³.

More complex database queries using ORMs can be difficult to achieve, leading to the argument that time may be better spent learning SQL rather than learning a tool to avoid having to learn SQL⁴.

A man in a white shirt writing “database” on glass with a black marker
A man in a white shirt writing “database” on glass with a black marker
Photo by Campaign Creators on Unsplash

Going for a Ride with Sequelize

While I’ve had some experience working with Active Record in Ruby on Rails, Sequelize is my first foray into using an ORM in Node JS and JavaScript. As one of the most downloaded⁵ Node JS ORMs out there, it felt like a good starting point.

To get acquainted with Sequelize, which is promise-based, I played around with a sample project using Express while perusing the offical Sequelize documentation.

Setting up the sample project was straight-forward and allowed me to get right into making database inserts and queries.

Similar to Active Record, Sequelize uses models to define database tables. It is convention to put each data model in its own file (with a pluralized name), which is then put in a folder called “models”.

As a quick overview, in databases, relationships between data are typically visualized using entity-relationship diagrams. Associations between tables (or models) of related data are described in terms such as one-to-one, one-to-many and many-to-many relationships.

Two ERD tables: one with Travellers and one with Luggage. Each has a unique id.
Two ERD tables: one with Travellers and one with Luggage. Each has a unique id.
An entity-relationship diagram demonstrating a simple one-to-many relationship: An item of luggage belongs to one traveller, and a traveller can have many items of luggage.

In Sequelize, these relationships are defined by combining the following types of associations (which you can learn more about here):

  • HasOne
  • BelongsTo
  • HasMany
  • BelongsToMany

For example, for the one-to-many relationship between Travellers and Luggage, we would define it as:

const { traveller, luggage } = sequelize.models;traveller.hasMany(luggage);luggage.belongsTo(traveller);

Once relationships are defined, foreign keys are generated automatically by Sequelize when an insert is made into the database.

For queries into the database, Sequelize has a wide selection of methods available. A simple example is if we wanted to find all the information about the Luggage for the Traveller with the ID of 2:

// Sequelize
Luggage.findAll({ where: { traveller_id: 2 } });
// SQL equivalent
SELECT * FROM luggage WHERE traveller_id = 2;
/* If you wanted the information about the traveller and their luggage: */// Sequelize
Traveller.findByPk(2, { include: models.luggage });
// SQL equivalent
SELECT * FROM travellers, luggage
JOIN luggage ON travellers.id = luggage.traveller_id
WHERE travellers.id = 2;

Final Thoughts

Overall, I enjoyed learning a little about Sequelize. I found the syntax of defining relationships to be intuitive and really appreciated the automatic generation of foreign keys as that has been a pain-point for me in previous projects. But, while simple queries were a delight, I found queries involving more than one model with Sequelize’s syntax to be a challenge.

I’m now inspired to look into other Node JS ORM and query-building libraries like Objection.js and Knex for my next project.

Thanks for reading and let me know your thoughts on ORMs!

References

1 Object–relational mapping,Wikipedia https://en.wikipedia.org/wiki/Object%E2%80%93relational_mapping Retrieved Jan 8, 2021

2 SQL, Wikipedia https://en.wikipedia.org/wiki/SQL Retrieved Jan 8, 2021

3 Object-relational Mappers (ORMs), Full Stack Python https://www.fullstackpython.com/object-relational-mappers-orms.html Retrieved Jan 8, 2021

4 Node.js ORMs and why you shouldn’t use them, Thomas Hunter https://blog.logrocket.com/why-you-should-avoid-orms-with-examples-in-node-js-e0baab73fa5/ Retrieved Jan 8, 2021

5 Comparing bookshelf vs. knex vs. objection vs. orm vs. sequelize, NPM Compare https://npmcompare.com/compare/bookshelf,knex,objection,orm,sequelize Retrieved Jan 8, 2021

6 API Reference, Sequelize https://sequelize.org/master/manual/assocs.html Retrieved Jan 8, 2021

Full-Stack Web Developer based in Halifax, NS

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store