📖 Table of Contents
- Introduction to Databases
- MongoDB vs PostgreSQL: Key Differences
- Setting Up MongoDB
- Connecting MongoDB to Express.js
- Setting Up PostgreSQL
- Connecting PostgreSQL to Express.js
- Implementing CRUD Operations with a Database
- Environment Variables for Database Configuration
- Best Practices
- Conclusion
1. Introduction to Databases
Databases are essential for any web application to store, retrieve, and manage data efficiently.
- MongoDB: A NoSQL database that stores data in JSON-like documents. Great for unstructured data.
- PostgreSQL: A relational SQL database ideal for structured data with complex relationships.
2. MongoDB vs PostgreSQL: Key Differences
Feature | MongoDB | PostgreSQL |
---|---|---|
Type | NoSQL | SQL |
Schema | Flexible | Fixed Schema |
Scalability | Horizontal | Vertical |
Best for | Real-time apps, Document storage | Complex queries, Structured data |
Choose MongoDB for flexibility and PostgreSQL for structured and relational data.
3. Setting Up MongoDB
3.1 Install MongoDB Locally
- Download MongoDB from the official MongoDB website.
- Install MongoDB Compass (GUI tool for MongoDB).
3.2 Set Up MongoDB Connection URL
MONGODB_URI=mongodb://localhost:27017/express_crud_db
4. Connecting MongoDB to Express.js
4.1 Install MongoDB Dependencies
npm install mongoose
4.2 Create Database Configuration File
File: src/config/database.ts
import mongoose from 'mongoose';
const connectMongoDB = async () => {
try {
await mongoose.connect(process.env.MONGODB_URI || '');
console.log('MongoDB Connected');
} catch (error) {
console.error('MongoDB connection failed:', error);
process.exit(1);
}
};
export default connectMongoDB;
4.3 Update app.ts
import connectMongoDB from './config/database';
connectMongoDB();
4.4 Create a User Model
File: src/models/userModel.ts
import mongoose, { Schema, Document } from 'mongoose';
interface IUser extends Document {
name: string;
email: string;
}
const UserSchema: Schema = new Schema({
name: { type: String, required: true },
email: { type: String, required: true }
});
export default mongoose.model<IUser>('User', UserSchema);
5. Setting Up PostgreSQL
5.1 Install PostgreSQL Locally
- Download PostgreSQL from the official website.
- Install pgAdmin (GUI tool for PostgreSQL).
5.2 Create a Database
- Open
psql
or pgAdmin. - Run:
CREATE DATABASE express_crud_db;
5.3 Set Up PostgreSQL Connection URL
POSTGRESQL_URI=postgresql://user:password@localhost:5432/express_crud_db
6. Connecting PostgreSQL to Express.js
6.1 Install PostgreSQL Dependencies
npm install knex pg
6.2 Configure Knex.js
File: src/config/knex.ts
import knex from 'knex';
const db = knex({
client: 'pg',
connection: process.env.POSTGRESQL_URI,
pool: { min: 0, max: 7 }
});
export default db;
6.3 Create a Migration File
npx knex migrate:make create_users_table --knexfile src/config/knex.ts
File: src/migrations/<timestamp>_create_users_table.ts
export function up(knex) {
return knex.schema.createTable('users', (table) => {
table.increments('id').primary();
table.string('name').notNullable();
table.string('email').notNullable().unique();
});
}
export function down(knex) {
return knex.schema.dropTable('users');
}
Run the migration:
npx knex migrate:latest --knexfile src/config/knex.ts
6.4 Create a User Model
File: src/models/userModel.ts
import db from '../config/knex';
export const getAllUsers = () => db('users').select('*');
export const getUserById = (id: number) => db('users').where({ id }).first();
export const createUser = (user: { name: string; email: string }) => db('users').insert(user);
export const updateUser = (id: number, user: { name?: string; email?: string }) => db('users').where({ id }).update(user);
export const deleteUser = (id: number) => db('users').where({ id }).del();
7. Implementing CRUD Operations with Database
7.1 Update Controller for MongoDB
File: src/controllers/userController.ts
import User from '../models/userModel';
export const getUsers = async (req, res) => {
const users = await User.find();
res.json(users);
};
7.2 Update Controller for PostgreSQL
import { getAllUsers, getUserById, createUser, updateUser, deleteUser } from '../models/userModel';
export const getUsers = async (req, res) => {
const users = await getAllUsers();
res.json(users);
};
8. Environment Variables for Database Configuration
File: .env
MONGODB_URI=mongodb://localhost:27017/express_crud_db
POSTGRESQL_URI=postgresql://user:password@localhost:5432/express_crud_db
Update your app.ts
to load .env
:
import dotenv from 'dotenv';
dotenv.config();
9. Best Practices
- Use environment variables for sensitive data.
- Validate data before saving to the database.
- Use connection pools for PostgreSQL.
- Properly handle database connection errors.
- Avoid exposing raw database errors to the client.
10. Conclusion
- MongoDB: Great for dynamic, schema-less applications.
- PostgreSQL: Best for structured, relational data with strict validation.
Choose the database based on your project requirements.
✨ Your Express.js app is now connected to both MongoDB and PostgreSQL! 🚀
Author: Mohin Sheikh
Follow me on GitHub for more insights!
Top comments (0)