Seamlessly Integrating MongoDB with SvelteKit Using Prisma: A Comprehensive Guide


MongoDB in SvelteKit Projects: A Prisma ORM Implementation Tutorial

MongoDB Compass
Type ORM

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

  1. Create a cluster on mongodbmongodb creating cluster
  2. If you already have a cluster then go to Database > Data Services > Connectmongodb database connection -
  3. Select connection type, I’m choosing Driversmongodb select driver -
  4. Create a .env file in the root directory and paste the following code:env file Now paste the code

MongoDB with Prisma Type ORM

  1. Install mongodb, prisma and prisma client in the sveltekit project
    npm install mongodb
    npm i prisma -D
    npm i @prisma/clients
  2. Initialize Prisma in your project:
    npx prisma init
    This command creates a prisma folder in the root directory along with a schema.prisma file.
  3. 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")
  4. 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

  1. To efficiently manage your database, download and install MongoDB Compass from the MongoDB website.
  2. Log in to the MongoDB platform, navigate to your database, click the connect button, and choose MongoDB Compass.Copy the provided connection string.
  3. Open MongoDB Compass and paste the connection string in the input field to connect to your database.mongodb compass connection You can now manage your MongoDB database without using the website.

Using Prisma Type ORM

  1. Create a new database in MongoDB Compass. In my example, I've named the database momo.
  2. 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
  3. 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",
  4. 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