Database Operations in Node.js

From the Express.js cheat sheet · Database Integration · verified Jul 2026

Database Operations

Integrate databases with Express

javascript
// MongoDB with Mongoose
const mongoose = require('mongoose')
mongoose.connect('mongodb://localhost/myapp')

const User = mongoose.model('User', {
  name: String,
  email: String
})

app.get('/users', async (req, res) => {
  const users = await User.find()
  res.json(users)
})

// PostgreSQL with pg
const { Pool } = require('pg')
const pool = new Pool({
  connectionString: process.env.DATABASE_URL
})

app.get('/users', async (req, res) => {
  const result = await pool.query('SELECT * FROM users')
  res.json(result.rows)
})
💡 Use connection pooling for production
✅ Always handle database errors
⚡ Use indexes for better query performance
Back to the full Express.js cheat sheet