How to Integrate Express.js with an ORM Framework

There is one more improvement we can make to our blog application before we move on to the next step, that is to integrate our old models setup with an ORM framework.

There are some issues with our old setup. For example, notice that all the methods that are in charge of interacting with the database, such as create(), update(), delete(), and so on, they all rely on SQL queries. This will require you to have a decent understanding of SQL.

javascript
1static create(username, email, callback) {
2  const sql = "INSERT INTO users (username, email) VALUES (?, ?)"; // <===
3  db.run(sql, [username, email], function (err) {
4    callback(null, this.lastID);
5  });
6}

And also, we did not implement a way to make changes to an existing database table.

Recall that in one of the previous lessons, in order to add a new picture column to the users table, we deleted the old database to get a fresh start. In practice, you should always avoid doing that, especially in the production environment.

Overall, it is just a headache to implement everything ourselves, and the ORM framework is here to make our lives easier.

What is an ORM

ORM, which stands for Object-Relational Mapping, is a type of tools that allow you to work on databases on a higher level, by providing interfaces that are much easier to understand than SQL queries.

Essentially, an ORM does the same job as the user.js and post.js models we created before in our examples, except it is usually packed with more features. And because there is always a big community behind an ORM framework, you are less likely to encounter bugs. And the best part is, you don't have to write anything yourself.

There is an ORM framework for almost every language, and for JavaScript, you have many options, such as Sequelize, TypeORM, Drizzle, Prisma, and so on. In this course, we are using Prisma as an example, and we will be adding tutorials on the other ORM frameworks in the community section in the future.

Wait, there is more!

You need an account to access the rest of this lesson. Our course is 50% off for limited time only! Don't miss the opportunity!

šŸŽ‰ Create an Account šŸŽ‰