The Codex / Technologies / Express.js / Connecting Databases

Connecting Databases

Persisting data beyond memory - connecting Express to PostgreSQL/MySQL with Prisma, or MongoDB with Mongoose, and the connection pooling pattern.

What it is, in plain English: Every REST API example so far stored data in a plain JavaScript array, which resets every time the server restarts. Real applications persist data in a database. Prisma is the most popular modern ORM (Object-Relational Mapper) for SQL databases (PostgreSQL, MySQL, SQLite) -- it generates a type-safe client from a schema file. Mongoose serves the same role for MongoDB. Both let route handlers read and write data without writing raw SQL or MongoDB driver calls by hand.

From in-memory arrays to a real database

Every REST API example so far stored data in a plain array -- simple for learning, but it resets every time the server restarts and can't be shared across multiple server instances. Real apps connect to an actual database.

Prisma -- the modern standard for SQL databases

# npm install prisma @prisma/client
# npx prisma init   -- creates a schema.prisma file and .env entry
// schema.prisma -- define your data shape:
datasource db {
  provider = "postgresql"
  url      = env("DATABASE_URL")
}

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

model User {
  id    Int    @id @default(autoincrement())
  name  String
  email String @unique
}
# Create the actual database table from your schema:
npx prisma migrate dev --name init

Using Prisma in Express routes

import { PrismaClient } from "@prisma/client";
const prisma = new PrismaClient();

app.post("/users", async (req, res) => {
  const user = await prisma.user.create({
    data: { name: req.body.name, email: req.body.email },
  });
  res.status(201).json(user);
});

app.get("/users", async (req, res) => {
  const users = await prisma.user.findMany();
  res.json(users);
});

app.get("/users/:id", async (req, res) => {
  const user = await prisma.user.findUnique({
    where: { id: Number(req.params.id) },
  });
  if (!user) return res.status(404).json({ error: "Not found" });
  res.json(user);
});

app.delete("/users/:id", async (req, res) => {
  await prisma.user.delete({ where: { id: Number(req.params.id) } });
  res.status(204).send();
});

MongoDB with Mongoose -- the document-database alternative

// npm install mongoose
import mongoose from "mongoose";
await mongoose.connect(process.env.MONGODB_URI);

const userSchema = new mongoose.Schema({
  name:  { type: String, required: true },
  email: { type: String, required: true, unique: true },
});
const User = mongoose.model("User", userSchema);

app.post("/users", async (req, res) => {
  const user = await User.create(req.body);
  res.status(201).json(user);
});
Try It Yourself (Node.js logic)

Official Sources

The Codex links only to official documentation. No third-party tutorials.