To create an example API in Node.js with MongoDB using Prisma ORM, you’ll first need to set up a Node.js project and configure Prisma to use MongoDB. Below is a step-by-step guide to create a basic API.
Step 1: Set Up Your Project
- Initialize a Node.js Project:
mkdir prisma-mongodb-example cd prisma-mongodb-example npm init -y
-
Install Required Packages:
Installexpress
for building the API,prisma
for ORM, and@prisma/client
for Prisma Client.
npm install express prisma @prisma/client
- Install Prisma CLI:
npx prisma init
Step 2: Configure Prisma for MongoDB
-
Configure
.env
File:
Update the.env
file generated by Prisma to include your MongoDB connection string. For example:
DATABASE_URL="mongodb://localhost:27017/mydatabase"
-
Set Prisma Schema to Use MongoDB:
Update theprisma/schema.prisma
file to use MongoDB as the provider and define a model. Here is an example schema:
datasource db { provider = "mongodb" url = env("DATABASE_URL") } generator client { provider = "prisma-client-js" } model User { id String @id @default(auto()) @map("_id") @db.ObjectId name String email String @unique }
Step 3: Generate Prisma Client
Run the following command to generate the Prisma Client based on the schema:
npx prisma generate
Step 4: Create a Basic Express API
-
Create an
index.js
File:
This file will initialize the Express application and define the API routes.
const express = require('express'); const { PrismaClient } = require('@prisma/client'); const prisma = new PrismaClient(); const app = express(); app.use(express.json()); // Create a new user app.post('/users', async (req, res) => { const { name, email } = req.body; try { const user = await prisma.user.create({ data: { name, email }, }); res.json(user); } catch (error) { res.status(400).json({ error: error.message }); } }); // Get all users app.get('/users', async (req, res) => { const users = await prisma.user.findMany(); res.json(users); }); // Get a single user by ID app.get('/users/:id', async (req, res) => { const { id } = req.params; try { const user = await prisma.user.findUnique({ where: { id }, }); if (user) { res.json(user); } else { res.status(404).json({ error: 'User not found' }); } } catch (error) { res.status(500).json({ error: error.message }); } }); // Update a user by ID app.put('/users/:id', async (req, res) => { const { id } = req.params; const { name, email } = req.body; try { const user = await prisma.user.update({ where: { id }, data: { name, email }, }); res.json(user); } catch (error) { res.status(400).json({ error: error.message }); } }); // Delete a user by ID app.delete('/users/:id', async (req, res) => { const { id } = req.params; try { await prisma.user.delete({ where: { id }, }); res.json({ message: 'User deleted successfully' }); } catch (error) { res.status(500).json({ error: error.message }); } }); const PORT = process.env.PORT || 3000; app.listen(PORT, () => { console.log(`Server is running on http://localhost:${PORT}`); });
Step 5: Run the Application
- Run the Application:
node index.js
-
Test the Endpoints:
Use tools like Postman or cURL to test the CRUD operations for theUser
model.
Conclusion
This example demonstrates how to create a basic CRUD API in Node.js with MongoDB using Prisma ORM. You can expand this example by adding more models, relationships, and validation logic as needed for your application.
Discover more from Coursity
Subscribe to get the latest posts sent to your email.