MongoDB Compass
sveltekit
prisma
Type ORM
mongodb
We will follow these steps one by one -
- Create Mongodb cluster
- MongoDB with Prisma Type ORM
- MongoDB compass
- Using Prisma Type ORM
Create Mongodb cluster
- 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 codeDATABASE_URL = "mongodb+srv://momo:<password>@momo.xogao6r9.mongodb.net/momo?retryWrites=true&w=majority";
MongoDB with Prisma Type ORM
- 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:
This command creates anpx prisma init
prisma
folder in the root directory along with aschema.prisma
file. - Connect Prisma with mongodbOpen
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
MongoDB compass
- 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.
Using Prisma Type ORM
- Create a new database in MongoDB Compass. In my example, I've named the database
momo
. - Update
schema.prisma
to define your data model:
Then, generate the Prisma client:model opinion { id String @id @default(auto()) @map("_id") @db.ObjectId type String vote Int }
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