This guide will walk you through the process of connecting your Next.js 14 SaaS application to MongoDB using Prisma ORM. You'll learn how to set up a new MongoDB database, retrieve the necessary connection string, and configure it in your application.
- Visit the MongoDB website and sign in to your account or sign up if you don't have an account yet.
- Once logged in, navigate to the MongoDB Atlas dashboard and click on 'Create a New Cluster'. Follow the prompts to set up your cluster. This includes selecting your cloud provider, region, and instance size.
- After your cluster is created, click on the 'Database Access' tab on the left sidebar, then click 'Add New Database User'. Fill out the username and password fields and set the user privileges as needed.After your cluster is created, click on the 'Database Access' tab on the left sidebar, then click 'Add New Database User'. Fill out the username and password fields and set the user privileges as needed.
- In the MongoDB Atlas dashboard, click on the 'Clusters' tab on the left sidebar, then select your cluster.
- Click on the 'Connect' button and follow the instructions. Choose 'Connect your application' and copy the connection string provided. It usually starts with mongodb+srv://.
With your connection string in hand, edit the following .env line:
1
DATABASE_URL="paste the connection string here"
Make sure to replace username, password, and cluster-url with your actual MongoDB credentials and cluster information.
Run the following line in your terminal to generate prisma schema. Please make sure to run this while your Nextjs application is off.
1
npx prisma generate
After setting up your Prisma schema and generating the Prisma client, run the following command in your project's root directory:
1
npx prisma db push