0
0
Expressframework~5 mins

Why database integration matters in Express

Choose your learning style9 modes available
Introduction

Database integration helps your Express app save and get data easily. It makes your app useful by remembering information.

You want to store user sign-up details like names and emails.
You need to save and show product lists in an online store.
You want to keep track of messages in a chat app.
You need to save settings or preferences for each user.
You want to log events or errors for later review.
Syntax
Express
const express = require('express');
const app = express();
const { Client } = require('pg'); // Example for PostgreSQL

const client = new Client({
  connectionString: 'your-database-url'
});

client.connect();

app.get('/data', async (req, res) => {
  const result = await client.query('SELECT * FROM your_table');
  res.json(result.rows);
});

This example uses PostgreSQL with the 'pg' library.

Database connection is set up once and used in routes.

Examples
Example of connecting to MongoDB and fetching all users.
Express
(async () => {
  const { MongoClient } = require('mongodb');
  const client = new MongoClient('your-mongodb-url');
  await client.connect();
  const db = client.db('mydb');
  const collection = db.collection('users');
  const users = await collection.find().toArray();
})();
Example of adding data to a PostgreSQL database from a POST request.
Express
app.post('/add', async (req, res) => {
  const { name } = req.body;
  await client.query('INSERT INTO users(name) VALUES($1)', [name]);
  res.send('User added');
});
Sample Program

This Express app connects to a PostgreSQL database. It has two routes: one to get all users and one to add a new user. It shows how database integration lets your app save and retrieve data.

Express
const express = require('express');
const { Client } = require('pg');

const app = express();
app.use(express.json());

const client = new Client({
  connectionString: 'postgresql://user:password@localhost:5432/mydb'
});

client.connect();

app.get('/users', async (req, res) => {
  try {
    const result = await client.query('SELECT id, name FROM users');
    res.json(result.rows);
  } catch (err) {
    res.status(500).send('Error fetching users');
  }
});

app.post('/users', async (req, res) => {
  const { name } = req.body;
  try {
    await client.query('INSERT INTO users(name) VALUES($1)', [name]);
    res.send('User added');
  } catch (err) {
    res.status(500).send('Error adding user');
  }
});

app.listen(3000, () => {
  console.log('Server running on http://localhost:3000');
});
OutputSuccess
Important Notes

Always handle errors when working with databases to avoid crashes.

Keep your database credentials safe and do not hardcode them in real apps.

Use async/await to work smoothly with database calls in Express.

Summary

Database integration lets your Express app save and get data.

It is useful for user info, products, messages, and more.

Use libraries like 'pg' for PostgreSQL or 'mongodb' for MongoDB to connect your app.