DEV Community

Cover image for Getting Started With TypeORM and MongoDB
Kinanee Samson
Kinanee Samson

Posted on • Edited on

Getting Started With TypeORM and MongoDB

Since I stumbled across NoSQL databases, specifically document-oriented databases, I knew I had found the one for me. It is not that I see 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 begun personally and will still do so.

Different ORMs out there support MongoDB, but I will talk 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 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 while allowing newbies to use it with Javascript. However, if you to get its game-changing abilities you must use Typescript.

TypeORM supports multiple databases ranging from SQL databases like MySQL and Postgresql to NoSQL document-oriented databases like MongoDB and CockroachDB. Being an ORM, TypeORM exists as a layer on top of our application. It allows us to build our applications using Object-oriented programming principles when interacting with our data instead of dealing directly with 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 gives us unparalleled benefits.

Project Setup

Let's create a simple project using TypeORM and MongoDB with Express. The first thing we'll need to do is to open up a terminal and run the following command,

npx typeorm init --name projectName--database mongodb

Enter fullscreen mode Exit fullscreen mode

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 to start editing our projects.

cd projectName
Enter fullscreen mode Exit fullscreen mode

Now our folder structure should look like this

MyProject
├── src                  
│   ├── entity           
│   │   └── User.ts  
│   ├── migration       
│   ├── data-source.ts   
│   └── index.ts         
├── .gitignore         
├── package.json          
├── README.md             
└── tsconfig.json         
Enter fullscreen mode Exit fullscreen mode

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

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,
   ]
  })
Enter fullscreen mode Exit fullscreen mode

Next, we need to install Express.JS to create a basic server.

npm i express 
Enter fullscreen mode Exit fullscreen mode

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

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));
Enter fullscreen mode Exit fullscreen mode

Why TypeORM

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

  • It is simple to create 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 an intuitive way while 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 want to use 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 may have to write your queries differently. This is more ideal, instead of learning the APIs for a new ORM due to time factors.

  • TypeORM provides the full benefit of working with Typescript but it 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 while minimizing 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. Still, all the 10X developers I know use TypeORM so if you want to 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.

Top comments (0)