Typescript Express API with MongoDB, Mongoose and Decorators

3 min read 2 days ago
Published on Nov 12, 2024 This response is partially generated with the help of AI. It may contain inaccuracies.

Table of Contents

Introduction

In this tutorial, you'll learn how to create a TypeScript Express API that connects to MongoDB using Mongoose and decorators. This guide is designed for developers who want to enhance their Node.js applications with TypeScript's type safety and the power of decorators for cleaner code organization. By the end, you'll have a foundational understanding of how to set up your API, define models, and handle requests effectively.

Step 1: Install and Configure Mongoose

To get started, you'll need to install Mongoose and set up your MongoDB connection.

  1. Install Mongoose: Run the following command in your terminal:

    npm install mongoose
    
  2. Create a Connection: In your main application file (e.g., app.ts), include the following code to establish a connection to your MongoDB database:

    import mongoose from 'mongoose';
    
    mongoose.connect('mongodb://localhost:27017/your-database-name', {
      useNewUrlParser: true,
      useUnifiedTopology: true,
    }).then(() => {
      console.log('MongoDB connected successfully');
    }).catch(err => {
      console.error('MongoDB connection error:', err);
    });
    
  3. Check MongoDB Status: Ensure your MongoDB server is running. You can start it using:

    mongod
    

Step 2: Define Your Model

Next, you'll need to define a Mongoose model that represents the structure of your data.

  1. Create a Model File: Create a new file called User.ts in your models directory.

  2. Define the User Schema: Use the following code to define the schema and model:

    import mongoose, { Schema } from 'mongoose';
    
    const userSchema = new Schema({
      name: { type: String, required: true },
      email: { type: String, required: true, unique: true },
      password: { type: String, required: true },
    });
    
    const User = mongoose.model('User', userSchema);
    
    export default User;
    

Step 3: Set Up Your Controller

Controllers handle the logic for processing requests and returning responses.

  1. Create a Controller File: Create a file named UserController.ts.

  2. Define Controller Methods: Add methods for creating and retrieving users:

    import User from './User';
    
    export class UserController {
      async createUser(req, res) {
        const { name, email, password } = req.body;
        try {
          const newUser = await User.create({ name, email, password });
          res.status(201).json(newUser);
        } catch (error) {
          res.status(400).json({ error: error.message });
        }
      }
    
      async getUsers(req, res) {
        try {
          const users = await User.find();
          res.status(200).json(users);
        } catch (error) {
          res.status(400).json({ error: error.message });
        }
      }
    }
    

Step 4: Implement Decorators

TypeScript decorators can help you manage your routes and middleware more effectively.

  1. Install Required Dependencies: If you haven't already, install the type definitions for Express:

    npm install @types/express
    
  2. Create Decorators: Define decorators for your endpoint methods. For example:

    function Get(route: string) {
      return function (target: any, key: string) {
        // Logic to bind the route to the method
      };
    }
    
    function Post(route: string) {
      return function (target: any, key: string) {
        // Logic to bind the route to the method
      };
    }
    
  3. Use Decorators in Your Controller: Apply the decorators to your controller methods:

    export class UserController {
      @Post('/users')
      async createUser(req, res) { ... }
    
      @Get('/users')
      async getUsers(req, res) { ... }
    }
    

Conclusion

In this tutorial, you've learned how to set up a TypeScript Express API with MongoDB using Mongoose and decorators. You've covered:

  • Installing and configuring Mongoose for MongoDB connections
  • Defining models to represent your data
  • Creating controllers to handle API logic
  • Implementing decorators to manage your routes

As a next step, consider expanding your API functionality by adding more routes, implementing validation, or integrating authentication. This foundational knowledge will help you build robust and scalable applications.