• Что бы вступить в ряды "Принятый кодер" Вам нужно:
    Написать 10 полезных сообщений или тем и Получить 10 симпатий.
    Для того кто не хочет терять время,может пожертвовать средства для поддержки сервеса, и вступить в ряды VIP на месяц, дополнительная информация в лс.

  • Пользаватели которые будут спамить, уходят в бан без предупреждения. Спам сообщения определяется администрацией и модератором.

  • Гость, Что бы Вы хотели увидеть на нашем Форуме? Изложить свои идеи и пожелания по улучшению форума Вы можете поделиться с нами здесь. ----> Перейдите сюда
  • Все пользователи не прошедшие проверку электронной почты будут заблокированы. Все вопросы с разблокировкой обращайтесь по адресу электронной почте : info@guardianelinks.com . Не пришло сообщение о проверке или о сбросе также сообщите нам.

? Setting Up PostgreSQL with Prisma ORM in a Node.js Project (Using Docker)

Lomanu4 Оффлайн

Lomanu4

Команда форума
Администратор
Регистрация
1 Мар 2015
Сообщения
1,481
Баллы
155
In my recent Node.js project, I set up a PostgreSQL database using Prisma ORM—one of the most efficient and type-safe ORMs available. I used docker to run postgres on my linux machine

Here’s a detailed walkthrough of the setup—from pulling the Docker image to generating the Prisma client. If you're getting started with Prisma and PostgreSQL in Node.js, this guide is for you.

?️ Prerequisites


Make sure the following are installed:

Step 1: Pull PostgreSQL Docker Image


docker pull postgres
Step 2: Run PostgreSQL Container


docker run --name my-postgres -e POSTGRES_USER=admin -e POSTGRES_PASSWORD=secret -e POSTGRES_DB=mydb -p 5432:5432 -d postgres

? This sets up a PostgreSQL container with:

  • Username: admin
  • Password: secret
  • Database name: mydb
  • Port: Exposes DB on localhost:5432
Step 3: Init NodeJs project


npm init -y
Step 4: Install Prisma


npm install prisma --save-dev
npm install @prisma/client
npx prisma init
? Step 5: Configure .env


add DATABASE_URL in .env file

DATABASE_URL="postgresql://admin:secret@localhost:5432/mydb?schema=public"

  • admin: PostgreSQL username
  • secret: PostgreSQL password
  • localhost: Host of the DB server
  • 5432: PostgreSQL's default port
  • mydb: Database name
  • schema=public: Default schema in PostgreSQL
? Step 6: Define Your Prisma Schema


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

datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}

model User {
id Int @id @default(autoincrement())
email String @unique
name String?
createdAt DateTime @default(now())
}
⚙ Step 7: Migrate and Generate Prisma Client


npx prisma migrate dev --name init
npx prisma generate

--
migrate dev creates migration files and updates the DB
generate creates the Prisma client for querying

Step 8: Test the Database Connection


Let’s write a quick script to ensure everything’s working as expected.

Create a script.js file:


const { PrismaClient } = require('@prisma/client');
const prisma = new PrismaClient();

async function main() {
const user = await prisma.user.create({
data: {
email: 'abc@example.com',
name: 'Tushar',
},
});

console.log('User created:', user);

const allUsers = await prisma.user.findMany();
console.log('All users:', allUsers);
}

main()
.catch(e => {
console.error(e);
process.exit(1);
})
.finally(async () => {
await prisma.$disconnect();
});
Run the Script


node script.js

You should see something like:


User created: { id: 1, email: 'abc@example.com', name: 'Tushar', createdAt: 2025-05-18T... }
All users: [ { id: 1, email: 'abc@example.com', name: 'Tushar', createdAt: 2025-05-18T... } ]

? Congratulations! You've successfully connected Node.js to a PostgreSQL database running inside a Docker container using Prisma.


Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

 
Вверх Снизу