On this page
Database Integration
Node.js connects to many databases. This chapter covers MongoDB (NoSQL) and SQL with Prisma.
MongoDB with Mongoose
npm install mongoose
import mongoose from 'mongoose';
await mongoose.connect(process.env.DATABASE_URL);
const userSchema = new mongoose.Schema({
name: { type: String, required: true },
email: { type: String, required: true, unique: true },
createdAt: { type: Date, default: Date.now }
});
const User = mongoose.model('User', userSchema);
// Create
const user = await User.create({ name: 'Alice', email: '[email protected]' });
// Read
const users = await User.find();
const one = await User.findById(user._id);
const byEmail = await User.findOne({ email: '[email protected]' });
// Update
await User.findByIdAndUpdate(user._id, { name: 'Alice Smith' });
// Delete
await User.findByIdAndDelete(user._id);
Express + Mongoose
app.get('/api/users', async (req, res) => {
const users = await User.find().select('-__v');
res.json(users);
});
app.post('/api/users', async (req, res) => {
try {
const user = await User.create(req.body);
res.status(201).json(user);
} catch (err) {
res.status(400).json({ error: err.message });
}
});
SQL with Prisma
npm install prisma @prisma/client
npx prisma init
schema.prisma:
model User {
id Int @id @default(autoincrement())
name String
email String @unique
createdAt DateTime @default(now())
}
npx prisma migrate dev --name init
import { PrismaClient } from '@prisma/client';
const prisma = new PrismaClient();
// Create
const user = await prisma.user.create({
data: { name: 'Bob', email: '[email protected]' }
});
// Read
const users = await prisma.user.findMany();
const one = await prisma.user.findUnique({ where: { id: 1 } });
// Update
await prisma.user.update({
where: { id: 1 },
data: { name: 'Robert' }
});
// Delete
await prisma.user.delete({ where: { id: 1 } });
Connection Best Practices
- Store connection strings in environment variables
- Handle connection errors on startup
- Close connections gracefully on shutdown:
process.on('SIGINT', async () => {
await mongoose.connection.close();
process.exit(0);
});
Choosing a Database
| Use MongoDB when | Use SQL when |
|---|---|
| Flexible schema | Strict relationships |
| Document-oriented data | Transactions critical |
| Rapid prototyping | Complex queries/joins |
Both work excellently with Node.js — choose based on your data model, not hype.