Lädt...


🔧 Building a Movie Database with Prisma, Express, and MongoDB: A Beginner's Guide


Nachrichtenbereich: 🔧 Programmierung
🔗 Quelle: dev.to

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:

# 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:

# 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/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:

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:

// 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/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:

// 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:

// 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 Linkedin

...

🔧 Building a Movie Database with Prisma, Express, and MongoDB: A Beginner's Guide


📈 79.56 Punkte
🔧 Programmierung

🔧 Building a RESTful API with Prisma, Express, TypeScript, and PostgreSQL


📈 34.09 Punkte
🔧 Programmierung

🍏 Coollector Movie Database 4.20.8 - Personal movie and video collection manager.


📈 32.32 Punkte
🍏 iOS / Mac OS

🎥 Azure SQL Support in Prisma [10 of 37]| Full Stack Application with Azure SQL & Prisma for Beginners


📈 30.72 Punkte
🎥 Video | Youtube

🔧 Prisma Part 1: Your Easy Tutorial to Set up Prisma


📈 30.72 Punkte
🔧 Programmierung

🔧 Update to Prisma 5.18.0 in typegraphql-prisma-nestjs


📈 30.72 Punkte
🔧 Programmierung

🔧 Movie Database - find the perfect movie


📈 30.7 Punkte
🔧 Programmierung

🔧 Building a Simple Blog with MongoDB, Express JS, and Node in 5 Easy Steps


📈 29.87 Punkte
🔧 Programmierung

🔧 Building a Todo Application Backend with MongoDB and Express


📈 29.87 Punkte
🔧 Programmierung

🔧 Building a CRUD Application with Node.js, Express, and MongoDB


📈 29.87 Punkte
🔧 Programmierung

🔧 Building a scalable Node.js API with Express and MongoDB


📈 29.87 Punkte
🔧 Programmierung

🔧 Building a Secure REST API with Node.js, Express, and MongoDB


📈 29.87 Punkte
🔧 Programmierung

📰 Building a RAG Pipeline with MongoDB: Vector Search for Personalized Movie Picks


📈 29.84 Punkte
🔧 AI Nachrichten

📰 Building a RAG Pipeline with MongoDB: Vector Search for Personalized Movie Picks


📈 29.84 Punkte
🔧 AI Nachrichten

🔧 Fetching and Displaying Code Snippets Using Server Actions, Prisma and MongoDB & Syntax Highlighting


📈 29.74 Punkte
🔧 Programmierung

🔧 Building Custom Request Filters for PactJs Verifications in Express and Non-Express Environments


📈 28.92 Punkte
🔧 Programmierung

🔧 User authentication and authorization in Node.js, Express.js app, using Typescript, Prisma, Zod and JWT


📈 28.8 Punkte
🔧 Programmierung

🔧 How to Connect RESTful API & Express JS backend with MongoDB database?


📈 28.45 Punkte
🔧 Programmierung

🔧 NextJS Auth with NextAuth v5, Prisma and MongoDB


📈 28.12 Punkte
🔧 Programmierung

🔧 The Ultimate Guide to Prisma ORM: Transforming Database Management for Developers


📈 27.96 Punkte
🔧 Programmierung

🔧 A Beginner's Guide to API Development with Node.js and Express


📈 27.24 Punkte
🔧 Programmierung

🔧 Getting Started with Express.js and Node.js: A Beginner's Guide


📈 27.24 Punkte
🔧 Programmierung

🔧 A Simple Crud App With Prisma, Express, and PostgreSQL


📈 27.17 Punkte
🔧 Programmierung

🔧 Setting Up a Backend with Prisma, Express, and PostgreSQL


📈 27.17 Punkte
🔧 Programmierung

🔧 Getting Started with MongoDB: A Beginner's Guide


📈 26.56 Punkte
🔧 Programmierung

🔧 Getting Started with MongoDB: A Beginner's Guide;


📈 26.56 Punkte
🔧 Programmierung

🔧 MongoDB Beginner's Guide: A Step-by-Step Introduction


📈 26.56 Punkte
🔧 Programmierung

🔧 Understanding Sorting in MongoDB: A Beginner's Guide


📈 26.56 Punkte
🔧 Programmierung

🔧 Setup MongoDB replica set locally in docker or with Atlas for Prisma ORM


📈 26.5 Punkte
🔧 Programmierung

🎥 Task Manager Coding Project Tutorial – Next.js, React, Prisma, MongoDB


📈 26.5 Punkte
🎥 Video | Youtube

🔧 Next.js MongoDB Prisma Auth Template 🚀


📈 26.5 Punkte
🔧 Programmierung

matomo