,

Creating an API with Typescript, Express, MongoDB, Mongoose, and Decorators

Posted by

Typescript Express API with MongoDB, Mongoose and Decorators

Typescript Express API with MongoDB, Mongoose and Decorators

Typescript is a superset of JavaScript that adds static typing to the language. Express is a popular Node.js framework for building web applications. MongoDB is a NoSQL database that is commonly used for storing and managing data. Mongoose is an ORM (Object-Relational Mapping) library for MongoDB that simplifies interactions with the database. Decorators are a feature of Typescript that allow for the addition of metadata and functionality to classes and class members.

Combining Typescript, Express, MongoDB, Mongoose and Decorators allows for the creation of a powerful and scalable API. In this article, we will walk through the steps to create a basic API using these technologies.

Setting up the project

First, create a new Typescript project by running the following commands:

npm init
npm install typescript @types/node ts-node
npx tsc --init

Next, install the required dependencies:

npm install express @types/express mongoose @types/mongoose

Creating the Express server

Create a new file called app.ts and add the following code:

import express from 'express';

const app = express();

const port = 3000;

app.listen(port, () => {
  console.log(`Server running on port ${port}`);
});

Run the server by executing the command npx ts-node app.ts. You should see the message “Server running on port 3000” in the console.

Connecting to MongoDB using Mongoose

To connect to MongoDB using Mongoose, add the following code to app.ts:

import mongoose from 'mongoose';

const uri = 'mongodb://localhost:27017/mydatabase';

mongoose.connect(uri, {
  useNewUrlParser: true,
  useUnifiedTopology: true
}).then(() => {
  console.log('Connected to MongoDB');
}).catch((error) => {
  console.error('Error connecting to MongoDB', error);
});

Creating a model with Mongoose

Create a new file called models/User.ts and add the following code:

import { Schema, model } from 'mongoose';

const userSchema = new Schema({
  name: String,
  email: String,
  age: Number
});

const User = model('User', userSchema);

export default User;

Adding Decorators to the API

To add decorators to the API, install the reflect-metadata package:

npm install reflect-metadata

Add the following code to the top of app.ts:

import 'reflect-metadata';

Now you can add decorators to your classes and class members. For example, you can use the @Get decorator to define a route that responds to GET requests:

import express, { Request, Response } from 'express';
import { Get } from './decorators/routes';

class UserController {
  @Get('/users')
  getUsers(req: Request, res: Response) {
    // Logic to get users from the database
  }
}

const app = express();

const port = 3000;

app.listen(port, () => {
  console.log(`Server running on port ${port}`);
});

With these steps, you have created a basic Typescript Express API with MongoDB, Mongoose, and Decorators. You can expand on this foundation to build more complex and feature-rich APIs.

0 0 votes
Article Rating
1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@piotrszymanski8325
7 months ago

M8, you are one of the best tutors, nice, clean, no trash talking, perfect tempo, pure and calm voice, and most important – pure essence. I keep fingers corssed for your success as a tutor.