ORMs in JavaScript
Tags: database, javascript, programming, sql
Published: 2022-06-04 18:32:40

---
title: ORMs in JavaScript
published: true
description: 
tags: Database, JavaScript, programming, SQL
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/y8jdgtyvw8n4y2axqo3q.jpg
# Use a ratio of 100:42 for best results.
---

## 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](https://en.wikipedia.org/wiki/Object%E2%80%93relational_mapping)

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/q0gy4d4ckq4qy2tvjah4.png)


### 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 :
```sql
$value = SELECT * FROM Users WHERE name = 'Singh' 
```
In an ORM, the above query would look like this :
```js
value = collection.query(day = 'Monday')
```
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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/obqbemyt9jw21o73l8ol.png)

> 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](https://github.com/typeorm/typeorm)

It is currently the most popular ORM library for projects written in TypeScript with Github stars of 28k+. It supports both [Data Mapper](https://github.com/typeorm/typeorm/blob/master/docs/active-record-data-mapper.md#what-is-the-data-mapper-pattern) and [Active Record](https://github.com/typeorm/typeorm/blob/master/docs/active-record-data-mapper.md#what-is-the-active-record-pattern) 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:
```js
import { Photo } from "./entity/Photo"
import { AppDataSource } from "./index"

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

await AppDataSource.manager.save(photo)
```

### 2. Sequelize
![Sequelize logo](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/sbtnrfnnm0l2lwdxicp9.png)

> 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](https://sequelize.org/)

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:

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

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:

```js
const users = await sequelize.query('SELECT * FROM users', {
  model: Users
});
```
### 3. Prisma
![Prisma Logo](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1rkpqx2ppulwhx2rx814.png)

> 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](https://www.prisma.io/)

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:

```js
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 })
}
```
The above code will return a JavaScript object like this:
```js
[
  {
    email: 'alice@prisma.io',
    id: 1,
    name: 'Alice'
  }
]
```

### 4. Knex
![Knex logo](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tlxs9tu2w701ef3k35q8.png)

> 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](http://knexjs.org/)

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:
```js
  const newUser = await knex('users').insert({ user_name: 'Tim' })
```
## 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**](https://developer.mozilla.org/en-US/docs/Glossary/MVC) 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
* www.unsplash.com/photos/tZIrJ3CgK_Y
* www.educative.io/edpresso/what-is-object-relational-mapping
* www.sitepoint.com/javascript-typescript-orms/