DEV Community

Cover image for ORMs in JavaScript
G.Singh
G.Singh

Posted on

ORMs in JavaScript

Introduction

As a relative newbie in programming, I came across this term for the first time in my Bootcamp and it sure was very intimidating. But after using an ORM in the ruby-on-rails app, I got a high-level understanding of what they are and why we use them. In this article, I will try to share what I have learned so far about this Buzzword and will help you explore popular ORMs in Javascript.

What is ORM?

Object-relational mapping in computer science is a programming technique for converting data between type systems using object-oriented programming languages. This creates, in effect, a "virtual object database" that can be used from within the programming language.
-- Wikipedia

In other words, ORM is a technique for storing, retrieving, updating, and deleting (CRUD) data from a relational database in an object-oriented program. To do so, ORM utilizes a data layer to manage translation between models(Objects/classes) and database, For eg. Active Records ORM library in rails.

ORM Illustration

Why do we need ORM?

There are many benefits of using ORM to manipulate databases instead of using database management systems like PostgreSQL, MySQL etc. to do the same.

  • We can keep using the language that we're already familiar with. For example; We don't need to learn the syntax of PostgresSQL in order to make queries to the database in our React-node.js application. We can use an ORM library written for Javascript in order to do so.
  • ORM hides the complex process under the hood and lets us worry about high-level implementation.
  • ORM queries are more tightly integrated into our programs and make it easy for testing.
  • ORM can make our application more secure and provide protection from SQL injection attacks.

Example

To get a user with the name 'Singh' from the Users table, we use a query like this in Postgres :

$value = SELECT * FROM Users WHERE name = 'Singh' 
Enter fullscreen mode Exit fullscreen mode

In an ORM, the above query would look like this :

value = collection.query(day = 'Monday')
Enter fullscreen mode Exit fullscreen mode

As you can see, we're writing the same Query using JavaScript, the language we already know.

Popular ORMs in JavaScript

In this section, I'll introduce some of the popular and open-source ORMs in JavaScript. I've sorted them into this list according to their Github stars

1. Typeorm

Typeorm Logo

TypeORM is an ORM that can run in NodeJS, Browser, Cordova, PhoneGap, Ionic, React Native, NativeScript, Expo, and Electron platforms and can be used with TypeScript and JavaScript (ES5, ES6, ES7, ES8).
-- source

It is currently the most popular ORM library for projects written in TypeScript with Github stars of 28k+. It supports both Data Mapper and Active Record of choice. Due to this, developers with Java and Ruby background feel pretty comfortable using it.

Inserting a photo to Database using TypeORM looks something like this:

import { Photo } from "./entity/Photo"
import { AppDataSource } from "./index"

const photo = new Photo()
photo.name = "Dogs playing poker" 

await AppDataSource.manager.save(photo)
Enter fullscreen mode Exit fullscreen mode

2. Sequelize

Sequelize logo

Sequelize is a modern TypeScript and Node.js ORM for Postgres, MySQL, MariaDB, SQLite and SQL Server, and more. Featuring solid transaction support, relations, eager and lazy loading, read replication and more.
-- source

This is my favourite ORM library because of its excellent documentation that contains code examples of almost every use case.

Adding new column to Users table in Seqerlize would looks something like this:

const jane = await User.create({
  username: 'janedoe',
  birthday: new Date(1980, 6, 20),
});
const users = await User.findAll();
Enter fullscreen mode Exit fullscreen mode

Sequelize also supports raw SQL statements that give flexibility to developers and allows the use of more complex queries. For example, we can do this:

const users = await sequelize.query('SELECT * FROM users', {
  model: Users
});
Enter fullscreen mode Exit fullscreen mode

3. Prisma

Prisma Logo

Next-generation Node.js and TypeScript ORM, helps app developers build faster and make fewer errors with an open source database toolkit for PostgreSQL, MySQL, SQL Server, SQLite, MongoDB and CockroachDB.
-- source

Prisma is slightly different from other ORMs since it uses a schema file to map all the tables and columns instead of using object models.

Integrating Prisma into a project is quite a hassle at first but it is a more powerful ORM as compared to others and it also provides its robust GUI and CLI to easily manipulate and visualize data.

An example of adding a user to database using Prisma looks something like this:

async function main() {
  await prisma.user.create({
    data: {
      name: 'Alice',
      email: 'alice@prisma.io',
    },
  })

  const allUsers = await prisma.user.findMany()
  console.dir(allUsers, { depth: null })
}
Enter fullscreen mode Exit fullscreen mode

The above code will return a JavaScript object like this:

[
  {
    email: 'alice@prisma.io',
    id: 1,
    name: 'Alice'
  }
]
Enter fullscreen mode Exit fullscreen mode

4. Knex

Knex logo

Knex.js is SQL query builder for PostgreSQL, CockroachDB, MSSQL, MySQL, MariaDB, SQLite3, Better-SQLite3, Oracle, and Amazon Redshift designed to be flexible, portable, and fun to use.
-- source

Knex.js is the most performant ORB library that can run on both node.js and browser.

Inserting a row in pre-populated table would look something like this in Knex:

  const newUser = await knex('users').insert({ user_name: 'Tim' })
Enter fullscreen mode Exit fullscreen mode

Conclusion

Writing SQL code to CRUD a relational database in a JavaScript application can be a time-consuming activity. It also requires in-depth knowledge of databases and our ability to code in SQL.

ORMs increase developers' productivity by building highly-abstract database models and automagically generating SQL code. ORMs also make it easier to separate business logic from user-interface logic and offer more flexibility thus we can easily implement Model-View-Controller pattern to our application.

But ORMs still have their drawbacks. Complex ORM queries can lead to performance issues if not written properly. They also abstract away the database layer and due to this, new developers without SQL experience lack the proper understanding of what's going on under the hood. That can be a hindrance when something goes wrong and can be time-consuming to debug our application.

Developers need to do their research before adding an ORM to their application. Since there are many open-source ORMs available, some are better than others in terms of documentation, ease of use and scalability.

References

Top comments (0)