DEV Community

Mohin Sheikh
Mohin Sheikh

Posted on

Connecting an Express.js Application to MongoDB and PostgreSQL: A Step-by-Step Guide for Beginners

Image description

📖 Table of Contents

  1. Introduction to Databases
  2. MongoDB vs PostgreSQL: Key Differences
  3. Setting Up MongoDB
  4. Connecting MongoDB to Express.js
  5. Setting Up PostgreSQL
  6. Connecting PostgreSQL to Express.js
  7. Implementing CRUD Operations with a Database
  8. Environment Variables for Database Configuration
  9. Best Practices
  10. 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

3.2 Set Up MongoDB Connection URL

MONGODB_URI=mongodb://localhost:27017/express_crud_db
Enter fullscreen mode Exit fullscreen mode

4. Connecting MongoDB to Express.js

4.1 Install MongoDB Dependencies

npm install mongoose
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

4.3 Update app.ts

import connectMongoDB from './config/database';
connectMongoDB();
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

5.3 Set Up PostgreSQL Connection URL

POSTGRESQL_URI=postgresql://user:password@localhost:5432/express_crud_db
Enter fullscreen mode Exit fullscreen mode

6. Connecting PostgreSQL to Express.js

6.1 Install PostgreSQL Dependencies

npm install knex pg
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

6.3 Create a Migration File

npx knex migrate:make create_users_table --knexfile src/config/knex.ts
Enter fullscreen mode Exit fullscreen mode

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');
}
Enter fullscreen mode Exit fullscreen mode

Run the migration:

npx knex migrate:latest --knexfile src/config/knex.ts
Enter fullscreen mode Exit fullscreen mode

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();
Enter fullscreen mode Exit fullscreen mode

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);
};
Enter fullscreen mode Exit fullscreen mode

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);
};
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Update your app.ts to load .env:

import dotenv from 'dotenv';
dotenv.config();
Enter fullscreen mode Exit fullscreen mode

9. Best Practices

  1. Use environment variables for sensitive data.
  2. Validate data before saving to the database.
  3. Use connection pools for PostgreSQL.
  4. Properly handle database connection errors.
  5. 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)