backendnodejsdatabases

Building Robust Backend Systems with Node.js, Express, and Databases

By Samvel Avagyan
Picture of the author
Published on
Backend development with Node.js and databases

Node.js, Express, and databases like MongoDB and PostgreSQL form a powerful tech stack for building modern backend systems. This combination provides the performance, flexibility, and reliability needed for today's web applications.

Why Choose This Stack


The Node.js ecosystem offers unparalleled speed and efficiency for backend development. Express provides a minimal yet robust framework for building APIs and web applications. When combined with the right database, this stack can support applications of any scale—from simple prototypes to enterprise solutions handling millions of users.

Getting Started with Node.js and Express


Setting up a basic Node.js and Express application is straightforward and requires minimal configuration.

Setting Up Your Project

  1. Initialize a new Node.js project:

    mkdir my-backend-app
    cd my-backend-app
    npm init -y
    
  2. Install Express:

    npm install express
    
  3. Create a basic server: Create a file named app.js with the following code:

const express = require('express');
const app = express();
const port = process.env.PORT || 3000;

// Middleware for parsing JSON
app.use(express.json());

// Basic route
app.get('/', (req, res) => {
  res.json({ message: 'Welcome to our API!' });
});

// Start the server
app.listen(port, () => {
  console.log(`Server running on port ${port}`);
});

Working with MongoDB in Node.js


MongoDB is a popular NoSQL database that works exceptionally well with Node.js due to its JSON-like document structure.

Connecting to MongoDB

Install the MongoDB driver:

npm install mongodb

Then, connect to your MongoDB database:

const { MongoClient } = require('mongodb');
const uri = "mongodb://localhost:27017";
const client = new MongoClient(uri);

async function connectToDatabase() {
  try {
    await client.connect();
    console.log("Connected to MongoDB");
    const database = client.db("my_database");
    return database;
  } catch (error) {
    console.error("Database connection error:", error);
    process.exit(1);
  }
}

module.exports = { connectToDatabase };

Creating a REST API with Express and MongoDB

const express = require('express');
const { connectToDatabase } = require('./db');
const app = express();
const port = 3000;

app.use(express.json());

let db;

// Connect to database before starting server
connectToDatabase()
  .then(database => {
    db = database;
    app.listen(port, () => {
      console.log(`Server running on port ${port}`);
    });
  });

// Create a new user
app.post('/users', async (req, res) => {
  try {
    const user = req.body;
    const result = await db.collection('users').insertOne(user);
    res.status(201).json({ id: result.insertedId, ...user });
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

// Get all users
app.get('/users', async (req, res) => {
  try {
    const users = await db.collection('users').find().toArray();
    res.json(users);
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

Working with PostgreSQL in Node.js


PostgreSQL is a powerful relational database that excels at handling structured data with complex relationships.

Setting Up PostgreSQL Connection

Install the PostgreSQL client for Node.js:

npm install pg

Create a database connection:

const { Pool } = require('pg');

const pool = new Pool({
  user: 'postgres',
  host: 'localhost',
  database: 'myapp',
  password: 'password',
  port: 5432,
});

module.exports = {
  query: (text, params) => pool.query(text, params),
};

Building a REST API with Express and PostgreSQL

const express = require('express');
const db = require('./db');
const app = express();
const port = 3000;

app.use(express.json());

// Create a new product
app.post('/products', async (req, res) => {
  try {
    const { name, price, category } = req.body;
    const result = await db.query(
      'INSERT INTO products (name, price, category) VALUES ($1, $2, $3) RETURNING *',
      [name, price, category]
    );
    res.status(201).json(result.rows[0]);
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

// Get all products
app.get('/products', async (req, res) => {
  try {
    const result = await db.query('SELECT * FROM products');
    res.json(result.rows);
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

app.listen(port, () => {
  console.log(`Server running on port ${port}`);
});

Choosing Between MongoDB and PostgreSQL


The choice between MongoDB and PostgreSQL depends on your application's needs:

Choose MongoDB when:

  • Your data structure is complex or varies frequently
  • You need horizontal scaling
  • Your application requires high write throughput
  • You're working with unstructured or semi-structured data

Choose PostgreSQL when:

  • Data integrity and complex transactions are critical
  • Your data has many relationships between entities
  • You need powerful querying capabilities and complex JOINs
  • Compliance with ACID properties is required

Best Practices for Node.js Backend Development


  1. Use async/await for handling asynchronous operations
  2. Implement proper error handling in all routes and middleware
  3. Structure your application with separation of concerns (routes, controllers, services)
  4. Use environment variables for configuration settings
  5. Implement input validation to prevent security vulnerabilities
  6. Add comprehensive logging for debugging and monitoring
  7. Write tests for critical functionality

Conclusion


Building backend applications with Node.js, Express, and databases like MongoDB or PostgreSQL provides a solid foundation for modern web applications. This stack offers the flexibility to handle various use cases while maintaining performance and developer productivity. As you develop more complex applications, you can extend this foundation with authentication, caching, background jobs, and other advanced features.