This example shows how to use Prisma with MongoDB and use Prisma Client in a Node.js script to read and write data in a MongoDB database. You can find the database schema in ./prisma/schema.prisma.
The example consists of two parts:
tests/prisma.test.ts: Jest test (in TypeScript) with a variety of Prisma Client queries and assertions to showcase access patternssrc/prisma-examples: TypesScript files containing different Prisma Client queries
Download this example:
npx try-prisma@latest --template databases/mongodb
Then, navigate into the project directory:
cd mongodb
Alternative: Clone the entire repo
Clone this repository:
git clone git@github.com:prisma/prisma-examples.git --depth=1
Install npm dependencies:
cd prisma-examples/databases/mongodb
npm install
Run the following command from the mongodb folder to start MongoDB:
docker compose up -d
Note: The
docker-compose.ymlis where the root username and password are set with theMONGO_INITDB_ROOT_USERNAMEMONGO_INITDB_ROOT_PASSWORDenv vars
Prisma uses the DATABASE_URL environment variable defined in the .env file (in the same folder as package.json) to connect to the database.
Create the file:
touch .envThen add the following line:
DATABASE_URL="mongodb://root:prisma@localhost:27017/prisma-mongo?authSource=admin&retryWrites=true&w=majority"
Generate Prisma Client using the following command:
npx prisma generateTo run the test in tests/prisma.test.ts, run the following command:
npm run testTo run the example scripts in src/prisma-examples, run the following commands:
npm run script:create-user
npm run script:find-user
npm run script:update-user
npm run script:delete-user
npm run script:create-user-post
npm run script:find-posts- Check out the Prisma docs
- Join our community on Discord to share feedback and interact with other users.
- Subscribe to our YouTube channel for live demos and video tutorials.
- Follow us on X for the latest updates.
- Report issues or ask questions on GitHub.