Seamlessly Integrating MongoDB with SvelteKit Using Prisma: A Comprehensive Guide


Create a cluster on mongodb

If you already have a cluster then go to Database > Data Services > Connect

Select connection type, I’m choosing Drivers

Create a .env file in the root directory and paste the following code:
Now paste the code
DATABASE_URL =
"mongodb+srv://momo:<password>@momo.xogao6r9.mongodb.net/momo?retryWrites=true&w=majority";
Install mongodb, prisma and prisma client in the sveltekit project
npm install mongodb
npm i prisma -D
npm i @prisma/clients
Initialize Prisma in your project:
npx prisma init
This command creates a prisma folder in the root directory along with a schema.prisma file.
Connect Prisma with mongodb
Open schema.prisma and add the following configuration:
generator client {
provider = "prisma-client-js"
}
datasource db {
provider = "mongodb"
url = env("DATABASE_URL")
}
To ease working with Prisma and MongoDB, consider installing these extensions for VS Code:
for schema formatting Prisma - Visual Studio Marketplace
to directly interact with your database. MongoDB for VS Code - Visual Studio Marketplace
To efficiently manage your database, download and install MongoDB Compass from the MongoDB website.
Log in to the MongoDB platform, navigate to your database, click the connect button, and choose MongoDB Compass.
Copy the provided connection string.
mongodb+srv://momo:<password>@momo.xogao6r9.mongodb.net/
Open MongoDB Compass and paste the connection string in the input field to connect to your database.
You can now manage your MongoDB database without using the website.
Create a new database in MongoDB Compass. In my example, I've named the database momo.
Update schema.prisma to define your data model:
model opinion {
id String @id @default(auto()) @map("_id") @db.ObjectId
type String
vote Int
}
Then, generate the Prisma client:
npx prisma generate
In your SvelteKit endpoint +page.server.js, add the following code to interact with the database:
import { PrismaClient } from "@prisma/client";
const prisma = new PrismaClient();
async function mainA() {
const creatingData = await prisma.opinion.create({
data: {
vote: 1117,
type: "kabooz",
},
});
console.log(creatingData);
}
mainA();
Access the route in your browser to see a new document created in MongoDB Compass. You will see a document created in the mongodb compass

Improve caching and performance in SvelteKit by importing images from src/lib instead of static. Learn why and how this approach works.