Node JS - Prisma - MongoDB Replica Set for Prisma Queries Running

Best Way – MongoDB Replica Set for Prisma Queries Running – Prisma #15

()

In this blog, we will explore how to resolve the issue of “MongoDB Replica Set for Prisma queries running”. This error commonly occurs after setting up MongoDB in Prisma ORM and running database queries. Let’s dive in and check it out now

Best Way - MongoDB Replica Set for Prisma Queries Running

In the realm of modern web development, managing databases efficiently is paramount. One such powerful database management system is MongoDB, which, when combined with Prisma ORM, provides a robust solution for handling database operations. However, users often encounter an error when running Prisma queries on MongoDB due to the requirement for a replica set configuration. We will delve into the intricacies of configuring a MongoDB replica set for Prisma queries and provide a comprehensive step-by-step guide to resolve this issue.

Understanding the Error – MongoDB Replica Set for Prisma Queries Running

The error message you’re seeing below indicates that Prisma is trying to perform transactions on your MongoDB database, which requires the MongoDB server to be configured as a replica set.

// Import the data into the corresponding Prisma model
for (const item of data) {
   await prisma[prismaModel].create(
   Prisma needs to perform transactions, which requires your MongoDB server to be run as a replica set.
   https://pris.ly/d/mongodb-replica-set
   at In.handleRequestError (/var/www/html/project-folder/node_modules/@prisma/client/runtime/library.js:122:6877)
   at In.handleAndLogRequestError (/var/www/html/project-folder/node_modules/@prisma/client/runtime/library.js:122:6211)
   at In.request (/var/www/html/project-folder/node_modules/@prisma/client/runtime/library.js:122:5919)
   at async l (/var/www/html/project-folder/node_modules/@prisma/client/runtime/library.js:127:11167)
   at async main (/var/www/html/project-folder/prisma/mongodb/import.js:28:17) {
   code: 'P2031',
   clientVersion: '5.15.1',
   meta: { modelName: 'User' }
}

https://www.prisma.io/docs/orm/overview/databases/mongodb#replica-set-configuration

MongoDB only allows you to start a transaction on a replica set. Prisma ORM uses transactions internally to avoid partial writes on nested queries. This means we inherit the requirement of needing a replica set configured.

So we need to resolve this issue for running MongoDB through Prisma ORM.

Replica set configuration​

Why Replica Sets?

A MongoDB replica set is a group of mongod instances that maintain the same data set, providing redundancy and high availability. Replica sets are essential for production deployments as they ensure data is replicated across multiple servers, protecting against data loss and enabling automatic failover. When one server goes down, another can take over, ensuring continuous availability of the database.

Step-by-Step Guide to Configure MongoDB Replica Set on Linux

To set up a MongoDB replica set on a Linux system, you’ll need to follow several detailed steps. These include installing MongoDB, configuring the mongod.conf file, starting and stopping MongoDB services, and using mongosh for replica set operations. Below are the full details:

  1. Stop MongoDB Service 

If you need to stop the MongoDB service:

sudo systemctl stop mongod
  1. Configure mongod.conf

Edit the mongod.conf file for each MongoDB instance to set the replica set name.

sudo nano /etc/mongod.conf

Add or modify or uncomment the following lines in mongod.conf:

replication:
  replSetName: "rs0"
  1. Start MongoDB Service

Start the MongoDB service on each server.

sudo systemctl start mongod

To enable MongoDB to start on boot:

sudo systemctl enable mongod
  1. Connect to MongoDB Using mongosh

Install mongosh if it is not already installed:

npm install -g mongosh

Connect to one of the MongoDB instances using mongosh:

mongosh --host localhost --port 27017
  1. Initiate the Replica Set 

Once connected to one of the MongoDB instances, initiate the replica set using the following commands:

rs.initiate()

6. Verify the Replica Set Configuration

Check the status of the replica set to ensure it is configured correctly:

rs.status()

Configuring Prisma to Use MongoDB Replica Set

  1. Update schema.prisma:
datasource db {
  provider = "mongodb"
  url      = env("DATABASE_URL")
}

generator client {
  provider = "prisma-client-js"
}

model User {
  id    String @id @default(auto()) @map("_id") @test.ObjectId
  email String @unique
  name  String
}

  

  1. Set DATABASE_URL in .env:
DATABASE_URL="mongodb://localhost:27017/mydatabase?replicaSet=rs0"
  1. Generate Prisma Client:
npx prisma generate
  1. Run Migrations:
npx prisma migrate deploy

5. Now working perfect :

Once these steps are completed, your Prisma setup should now be fully functional with the MongoDB replica set.

Conclusion

By following these steps, you will have successfully configured a MongoDB replica set on a Linux system. This configuration not only ensures data redundancy and high availability but also enables Prisma ORM to handle transactions correctly. Setting up a replica set is crucial for any production environment, as it provides a robust foundation for database operations, safeguarding against data loss and ensuring continuous service availability. With this setup, you can leverage the full power of MongoDB and Prisma ORM in your applications, enhancing both performance and reliability.

Check out Another blog:

Related another blog:

How useful was this post?

Click on a star to rate it!

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post?

About the author

Hello,
I'm a Software Developer & Blogger
✨ Top 2% ⭐ 5-Star Rating ⚡️ Full Time Freelancer ☸️ Preferred ✅ Verified
⚡️ I have 10+ years experience in IT industry.
⚡️ Skills: PHP, Laravel, Yii, WordPress, Symfony, Cake, CodeIgniter, Zend + Vite React, React.js, Node.js, Tailwind CSS, Material UI Tailwind CSS React, Vue.js, Angular.js, Vuex store, React Redux Store, React Query, React DOM, React Native Expo, Axios, Express, Mongo DB, AWS Cloud, Azure Cloud, GCloud, Three.js, WebGL, WebGi, GSAP, 3D Products Modelling etc.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *