Prisma is object-relational mapping used to generate type-safe schemas for your database servers. Everything has to be properly configured when creating a database to specify how the database will appear. Prisma removes the need for you to write database queries in such circumstances. As a result, you can create safe database access schemas for your database.
Prisma is widely used with SQL databases such as MySQL, SQLite, PostgreSQL, and Microsoft SQL. However, Prisma has support for NoSQL databases such as MongoDB. This allows you to take Prisma’s advantages to a huge ecosystem.
Additionally, you can use both SQL and NoSQL databases under the same database schema. This guide will help you learn how to configure a Prisma client for a NoSQL MongoDB database in Node.js.
This article assumes you have
a Node.js runtime runtime installed,
a MongoDB server, and,
MongoDB Atlas is installed on your computer.
First, create a new directory, mongodb-with-prisma
inside any path where you want your application to live. Open the created project directory using a terminal or a text editor. Here, we need to initialize Node.js in order to run a Node.js Prisma server locally. To start a Node.js project, use the following command inside the mongodb-with-prisma directory
:
npm init -y
Now we need the Node.js Prisma package available for this project. To install it, use the following command:npm install prisma
Also, Prisma requires the Prisma client to use the Prisma services and commands. To install it, run:npm install @prisma/client --save-dev
Finally, initialize Prisma by running the following command.npx prisma init
Alternatively, since you are exclusively running Prisma with MongoDB you can specify MongoDB as the datasource and provider as follows:npx prisma init --datasource-provider mongodb
This will automatically build a Prisma subdirectory. The directory will have a schema.prisma
file for writing the Prisma database schemas. This is where you begin configuring Prisma, modeling the database data and the database of your choice.
This file is ready to be configured to use MongoDB if you used the npx prisma init --datasource-provider
mongodb command.
There will also be a .env
file created in your working directory. Private and sensitive information, such as your database connection URI strings, are stored in this file.
When setting up Prisma with MongoDB we need to use the MongoDB Atlas. MongoDB may throw the error seen below upon executing the Prisma command.
This typically happens while executing a local MongoDB setup. To avoid this we will create a cloud database hosted by MongoDB Atlas and modify your connection string to reflect it to resolve this problem.
Head over to your MongoDB Atlas. Create a new cluster using the free MO Sandbox to be able to build your online MongoDB cluster as a free tier.
To set up this cluster, click connect to allow cluster access from anywhere.
To connect the cluster with your database, create a database user if you don’t have one, ensuring you remember the username and the password.
Finally, choose the connection method. Select connect your application. This connects your application to your cluster using MongoDB’s native drivers.
In this case, choose the Node.js drive and copy your pre-formatted connection string.
Ensure you replace the connection string <password>
parameter with the password set when creating the database user.
Using the updated string, open MongoDB Compass and create a new connection. Enter your connection string ensuring the username and password reflect your MongoDB Atlas user.
Click connect to connect to your cluster. This will give a visual UI that we can interact with the cloud-created MongoDB database cluster.
Now that the database is set, open the project’s .env
file and the MongoDB database connection string as:
To use the created MongoDB, add the connection string to the .env
file of your project. Here we are adding the parameter employee
as the database name we will use with Prisma. Replace other parameters with your connection credentials and paste them in your .env
file as the DATABASE_URL
parameter as follows:
1
DATABASE_URL = "mongodb+srv://username>:<password>@<cluster-url>employee/?retryWrites=true&w=majority"
The database is now set, let’s dive into the next step.
Here we are using employees as our database. Therefore, we need to model a schema using Prisma that will reflect the details of an employee in an actual database.
Let’s now model our Prisma schema from an employee. We will create a model that represents a database inside the schema.prisma
file, just below the datasource block as follows:
1 2 3 4 5 6 7 8 9 10 11 12
model employees { // This sets the id of the database. This parameter will be auto-generated by the MongoDB database Employee_id String @id @default(auto()) @map("_id") @db.ObjectId // Add the first name as a string Firstname String // Add the Surname as a string Surname String // Add the Email address as a string Email String // create a date field on when the data was added to MongoDB using the now() parameter Hired_on DateTime @default(now()) }
To test the above data model, run:prisma generate
We can now start using Prisma client.
Using Node.js, we will implement a Prisma client to connect with the database. This will allow us to add some data to the database and test if Prisma can connect and communicate with MongoDB.
To build a Prisma Node.js server, go ahead and create an app.js file and set up the Prisma client for MongoDB as follows:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
// first, import the Prisma client to access Prisma methods
const {
PrismaClient
} = require("@prisma/client");
// initialize the Prisma client for your application
const prisma = new PrismaClient();
// create an asynchronous main function
async function main() {
// connect to the database using Prisma connect() method
await prisma.$connect();
// using the Prisma create() method, add data based on the model fields
// Note: other fields as autogenerated, and no need to specify them here
await prisma.employee.create({
data: {
Firstname: "Kim",
Surname: "Larry",
Email: "test@gmail.com",
},
});
// Add another field using create() method
await prisma.employee.create({
data: {
Firstname: "Julie",
Surname: "Morgan",
Email: "test@gmail.com",
},
});
// you can find the added fields using findMany() method
const employees = await prisma.employee.findMany();
// log these added fields to the console
console.dir(employees, {
depth: Infinity
});
}
main()
// catch any erroes
.catch(console.error)
// disconnect the prisma client once all processes are executed
.finally(() => prisma.$disconnect());
This will add the data to the database using the Prisma create()
method.
To execute the above employee
client run the following command:
node app.js
This will log the added employees as shown above. To confirm if the execution of the Prisma client is connected to MongoDB, refresh your connected database on MongoDB compass and refresh. An employee’s database got created:
If you open it, you can confirm if the schema was correctly executed by the Prisma client and added the data to the database.
Now you can start using Prisma and MongoDB to build data-driven Node.js APIs.