The Best Typesafe ORM you are not using
Tags: node, typescript, mongodb, mysql
Published: 2024-06-05 14:45:06

Since I stumbled across NoSQL databases, specifically document-oriented databases, I knew I had found the one for me. It is not that I find anything wrong about SQL databases but I'm not just that guy. I like to think about my data in terms of Objects. I started using MongoDB around 2020 and since then I've used it on almost all new projects I've started personally and will still do so. 

Different ORMs out there support [MongoDB](https://www.mongodb.com/), but I'm going to be talking about TypeORM in today's post. An ORM that works well with both SQL databases and MongoDB. In today's post, we will explore how to get started using TypeORM with MongoDB, and thus we will consider the following talking points.

- What is TypeORM 
- Project Setup and Integration with MongoDB
- Why TypeORM
- Should you use it

[TypeORM](https://typeorm.io/) is an Object Relational Mapper hence the (ORM) which is built to run in the browser, on the server aka Node.JS, Expo, and every single execution context that utilizes Javascript. TypeORM has excellent support for [Typescript](https://www.typescriptlang.org/) while allowing newbies to use it with Javascript too. However, if you want to get its game-changing abilities you need to use Typescript. 

TypeORM supports multiple databases ranging from SQL databases like MySQL and Postgresql to NoSQL document-oriented databases like MongoDB and [CockroachDB](https://www.cockroachlabs.com/). Being an ORM, TypeORM sits as a layer on top of our applications that allows us to build our applications using Object-oriented programming principles when interacting with our data as opposed to dealing directly with them. columns and rows which is the default for most SQL databases. As developers, we think about data more in terms of Objects than columns, and providing an API that allows us to interact with our data in a manner that we are already attuned to provides unparalleled benefits. 

Project Setup

Let's set up a simple project using TypeORM and MongoDB with [Express](https://expressjs.com/). The first thing we'll need to do is to open up a terminal and run the following command, 

```bash
npx typeorm init --name projectName--database mongodb

```

This command sets up a basic TypeORM project configured to work with MongoDB however there are still some things we'll need to handle personally. We'll need to provide the link to our MongoDB instance which could be hosted in the cloud or locally. Now we need to navigate into the directory so we can start editing our projects.

```bash
cd projectName
```

Now our folder structure should look like this

```tree
MyProject
├── src                  
│   ├── entity           
│   │   └── User.ts  
│   ├── migration       
│   ├── data-source.ts   
│   └── index.ts         
├── .gitignore         
├── package.json          
├── README.md             
└── tsconfig.json         
```

We'll first navigate to the `data-source.ts` and we'll make some changes to this file.

```typescript
import { User } from "./entity/User";

export const AppDataSource = new DataSource({
  type: "mongodb",
  url: process.env.DB_URL, // link to mongodb instance
  useUnifiedTopology: true,
  useNewUrlParser: true,
  synchronize: false,
  entities: [
    User,
   ]
  })
```
Next, we need to install `Express.JS` so we can create a server. 

```bash
npm i express 
```

Now you need to open up your `index.ts` folder inside the `src` folder and make the following updates to it.

```typescript
import express from 'express';
import { AppDataSource } from './data-source';
import {User} from './src/entity/user.ts';
import http from 'http';

const PORT = process.env.PORT;
const app = express();

const server = http.createServer(app);

app.get('/', async (req, res) => {
  const payload = await AppDataSource
    .mongoManger
    .find(User, {});
   return res.json(payload)
}

app.post('/user', async (req, res) => {
  const payload = req.body;
  const result = await AppDataSource
    .mongoManager
    .create(User, payload);
  return res.json(payload);
})

AppDataSource.initialize().then(async () => {
  console.log('connected to the database')
  server.listen(PORT, () => {
    console.log(`app running on port ${PORT}`)
  })
}).catch(error => console.log(error));
```

## Why TypeORM

Why should you consider using TypeORM, well if you didn't already notice;

- It is very easy to set up and get started creating a project with TypeORM, with just one command we were able to spin up and install the template and dependencies for our project. This is especially useful if you new to TypeORM, the API for interacting with your data is presents itself in a very simple and intuitive way while still being complex enough for you to write just about any query you can think of.

- If you already know TypeORM but you've only used it with MySQL in the past and you are looking at using MongoDB as your new database, you'd feel just at home if you go with TypeORM. There's virtually little to no learning curve when you decide to use MongoDB although might have to write your queries differently. This is so much better than having to learn the APIs for a new ORM due to time factors.
 
- TypeORM provides the full benefit of working with Typescript but it still accommodates vanilla Javascript excellently to encourage incremental adoption. TypeORM also allows you to utilize the Active Record pattern or the DataMapper pattern when interacting with your data. The list of databases supported by TypeORM is almost endless, from MySQL, PostgreSQL, MongoDB, to CockroachDB. 

## Should you use it

Now we know all the nice shiny things about TypeORM, is it something we should even consider using given the short amount of time we have, and if you ask me for my personal opinion then I'd say yes. TypeORM will make your job so much easier, the developer experience is unparalleled.  Their documentation is simple and straight to the point. TypeORM also allows you to build your apps faster and it minimizes the overall amount of code you need to write because most things have already been thought about in advance. Ultimately the decision to use TypeORM boils down to you, but all the 10X developers I know use TypeORM so if you wanna build the next project you're not going to finish then absolutely use TypeORM.

What is your take on TypeORM? Would you consider using it for your next project? Do you already use TypeORM? and if yes what is your experience with using TypeORM? I'd love to know all this and more so you can and should leave your thoughts in the comment section below.