Cookie Consent by Free Privacy Policy Generator Aktuallisiere deine Cookie Einstellungen ๐Ÿ“Œ Building a Movie Database with Prisma, Express, and MongoDB: A Beginner's Guide


๐Ÿ“š Building a Movie Database with Prisma, Express, and MongoDB: A Beginner's Guide


๐Ÿ’ก Newskategorie: 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.96 Punkte

๐Ÿ“Œ Azure SQL Support in Prisma [10 of 37]| Full Stack Application with Azure SQL & Prisma for Beginners


๐Ÿ“ˆ 31.15 Punkte

๐Ÿ“Œ Prisma Part 1: Your Easy Tutorial to Set up Prisma


๐Ÿ“ˆ 31.15 Punkte

๐Ÿ“Œ Coollector Movie Database 4.20.8 - Personal movie and video collection manager.


๐Ÿ“ˆ 31.07 Punkte

๐Ÿ“Œ Building a Simple Blog with MongoDB, Express JS, and Node in 5 Easy Steps


๐Ÿ“ˆ 29.93 Punkte

๐Ÿ“Œ Building a CRUD Application with Node.js, Express, and MongoDB


๐Ÿ“ˆ 29.93 Punkte

๐Ÿ“Œ Building a Todo Application Backend with MongoDB and Express


๐Ÿ“ˆ 29.93 Punkte

๐Ÿ“Œ Movie Database - find the perfect movie


๐Ÿ“ˆ 29.54 Punkte

๐Ÿ“Œ User authentication and authorization in Node.js, Express.js app, using Typescript, Prisma, Zod and JWT


๐Ÿ“ˆ 28.62 Punkte

๐Ÿ“Œ Build a Basic Note-Taking App with MongoDB, Node.js, Express, and Bootstrap: A Step-by-Step Guide for Beginners


๐Ÿ“ˆ 28.53 Punkte

๐Ÿ“Œ How to Connect RESTful API & Express JS backend with MongoDB database?


๐Ÿ“ˆ 28.08 Punkte

๐Ÿ“Œ A Beginner's Guide to API Development with Node.js and Express


๐Ÿ“ˆ 27.78 Punkte

๐Ÿ“Œ Build Complete REST API Feature with Nest JS (Using Prisma and Postgresql) from Scratch - Beginner-friendly - PART 1


๐Ÿ“ˆ 27.56 Punkte

๐Ÿ“Œ Getting Started with MongoDB: A Beginner's Guide


๐Ÿ“ˆ 27.47 Punkte

๐Ÿ“Œ A Simple Crud App With Prisma, Express, and PostgreSQL


๐Ÿ“ˆ 27.09 Punkte

๐Ÿ“Œ Setup MongoDB replica set locally in docker or with Atlas for Prisma ORM


๐Ÿ“ˆ 26.79 Punkte

๐Ÿ“Œ Task Manager Coding Project Tutorial โ€“ Next.js, React, Prisma, MongoDB


๐Ÿ“ˆ 26.79 Punkte

๐Ÿ“Œ Next.js MongoDB Prisma Auth Template ๐Ÿš€


๐Ÿ“ˆ 26.79 Punkte

๐Ÿ“Œ Data Engineering and DataOps: A Beginner's Guide to Building Data Solutions and Solving Real-World Challenges


๐Ÿ“ˆ 26.49 Punkte

๐Ÿ“Œ API REST avec Prisma , PostgreSQL et Express


๐Ÿ“ˆ 25.57 Punkte

๐Ÿ“Œ Mastering API Calls in React: A Beginner's Guide to Building and Consuming REST APIs


๐Ÿ“ˆ 24.97 Punkte

๐Ÿ“Œ Building Your Own Blockchain: A Beginnerโ€™s Guide to Setting Up and Using Cosmos


๐Ÿ“ˆ 24.97 Punkte

๐Ÿ“Œ Building a RESTful API with Node.js and Express: A Step-by-Step Guide


๐Ÿ“ˆ 24.51 Punkte

๐Ÿ“Œ Building an AI webapp(HomeDec) with Hanko, NextJS, Prisma, Supabase and Replicate


๐Ÿ“ˆ 24.29 Punkte

๐Ÿ“Œ Building a serverless GraphQL API with NeonDB and Prisma


๐Ÿ“ˆ 24.29 Punkte

๐Ÿ“Œ Building an Admin Console With Minimum Code Using React-Admin, Prisma, and Zenstack


๐Ÿ“ˆ 24.29 Punkte

๐Ÿ“Œ Building a full stack app with Remix, Prisma, and Neon


๐Ÿ“ˆ 24.29 Punkte

๐Ÿ“Œ Authentication( SignUp and Login ) with Express,MongoDB and Jwt.


๐Ÿ“ˆ 24.26 Punkte

๐Ÿ“Œ Movie Explorer 2.6.2 - Movie and TV show catalog app.


๐Ÿ“ˆ 24.2 Punkte

๐Ÿ“Œ Build a Scalable REST API with TypeScript, Express, Drizzle ORM, and Turso Database: A Step-by-Step Guide


๐Ÿ“ˆ 24.18 Punkte

๐Ÿ“Œ Build Your Movie Recommendation System Using Amazon Personalize, MongoDB Atlas, and AWS Glue


๐Ÿ“ˆ 24.08 Punkte

๐Ÿ“Œ ORM, Prisma, and How You Should Build Your Next Backend Database Project


๐Ÿ“ˆ 23.96 Punkte

๐Ÿ“Œ A Developer's Guide to Database Sharding With MongoDB


๐Ÿ“ˆ 23.87 Punkte

๐Ÿ“Œ A Beginner's Guide to Radix Sort: Step-by-Step Guide and Python Code


๐Ÿ“ˆ 23.57 Punkte

๐Ÿ“Œ Svelte for Beginners: A Beginner's Guide to Building Web Applications


๐Ÿ“ˆ 23.45 Punkte











matomo