Building a Movie Database with Prisma, Express, and MongoDB: A Beginner's Guide
Published: 2024-01-10 20:17:54

Welcome to the world of web development, where databases are the backbone of dynamic applications. If you're starting your journey and looking for a powerful yet beginner-friendly solution, Prisma might be your gateway to simplified database interactions. In this guide, we'll walk through the process of creating a movie database using Prisma, Express, and MongoDB, offering a hands-on approach for beginners.

## Prisma: A Quick Overview

Prisma is an open-source database toolkit that acts as a bridge between your application code and the database. It supports various databases like MySQL, PostgreSQL, SQLite, MongoDB, and more. The key highlight of Prisma is its type-safe and auto-generated query builder, allowing developers to interact with databases using their preferred programming language.

## Setting Up Your Project

Let's dive into the practical aspects. Open your terminal and follow these steps:

```bash
# Create a project directory
mkdir movie-database-prisma-express-mongodb

# Navigate into the project directory
cd movie-database-prisma-express-mongodb

# Initialize a JavaScript project
npm init -y

# Install necessary dependencies
npm install express @prisma/client dotenv
```

These commands set up a basic project structure, installing Express for building the web server, Prisma for database interactions, and dotenv for managing environment variables.

## Configuring Prisma for MongoDB

Now, let's set up Prisma to work with MongoDB. Execute the following commands in your terminal:

```bash
# Initialize Prisma
npx prisma init
```

This creates a `prisma` directory with essential files for your Prisma setup. Open `prisma/schema.prisma` and configure the datasource block to connect to your MongoDB:

```prisma
// prisma/schema.prisma
datasource db {
  provider = "mongodb"
  url      = env("DATABASE_URL")
}
```

Don't forget to create a `.env` file in your project root and add your MongoDB connection URL:

```env
DATABASE_URL="your-mongodb-connection-url"
```

Replace `"your-mongodb-connection-url"` with your actual MongoDB connection string.

## Building the Express Server

Now, let's explore the Express server setup in `server.js`:

```javascript
// server.js
import "dotenv/config";
import express from "express";
import routes from "./routes/index.js";

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

app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(routes);

app.get("/", (req, res) => {
  res.send("Working");
});

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

This script sets up a basic Express server, handling JSON and URL-encoded data. It also defines a simple `/` route that returns a "Working" message.

## Defining Routes and Controllers

Routes are defined in the `routes` directory, split into `movieRoutes.js` and `castRoutes.js`. These routes are then imported into `index.js` for a modular structure.

Controllers in `controllers/MovieController.js` and `controllers/CastController.js` handle the logic for storing, retrieving, updating, and deleting movies and casts.

## Prisma Data Model

The heart of Prisma lies in its data model, defined in `prisma/schema.prisma`. This structured representation of your database schema is used to auto-generate a Prisma Client.

```prisma
// prisma/schema.prisma
model Movie {
  id String @id @default(auto()) @map("_id") @db.ObjectId
  name String @unique
  created_at DateTime @default(now())
  Cast Cast[]
}

model Cast {
  id String @id @default(auto()) @map("_id") @db.ObjectId
  movieId String @db.ObjectId
  movie Movie @relation(fields: [movieId], references: [id])
  name String
  description String?
  created_at DateTime @default(now())
}
```

This snippet defines two models: `Movie` and `Cast`. The `Movie` model represents movies, and the `Cast` model represents the cast associated with each movie. Relationships between models are clearly defined.

## Prisma Client Configuration

In `DB/db.config.js`, the Prisma client is configured and exported:

```javascript
// DB/db.config.js
import { PrismaClient } from "@prisma/client";

const prisma = new PrismaClient({
  log: ["query"],
});

export default prisma;
```

## Using Prisma in Controllers

Controllers use the Prisma client for database operations. For instance, `CastController.js` retrieves all casts and stores new ones:

```javascript
// controllers/CastController.js
import prisma from "../DB/db.config.js";

export const getAllCast = async (req, res) => {
  // Retrieve all casts with associated movie details
  const casts = await prisma.cast.findMany({
    include: {
      movie: {
        select: {
          name: true,
          id: true,
        },
      },
    },
  });

  return res.json({ status: 200, casts });
};

export const store = async (req, res) => {
  // Store a new cast
  const { movie_id, name } = req.body;
  const cast = await prisma.cast.create({
    data: {
      movieId: movie_id,
      name: name,
    },
  });

  return res.json({ status: 200, cast, message: "Cast Added successfully!" });
};
```

## Conclusion

Congratulations! You've successfully set up a movie database using Prisma, Express, and MongoDB. This guide provides a foundation for building more complex applications and exploring the capabilities of Prisma in your web development journey. As you continue your exploration, remember to hide sensitive information like MongoDB credentials in the `.env` file. Happy coding!

Follow me on : [Github](https://github.com/jps27cse) [Linkedin](https://www.linkedin.com/in/jps27cse/)