Connecting to Databases

In JavaScript, connecting to databases typically happens on the server side using Node.js. Browsers do not directly connect to databases for security reasons. Instead, server-side code handles the database connection and queries.

Illustration of Connecting to Databases
Illustration of Connecting to Databases

💡 Key Concept

Node.js allows you to interact with databases using specific drivers or libraries tailored to each database type (e.g., MySQL, MongoDB, PostgreSQL).

Common Database Drivers & Libraries for Node.js

Popular Node.js Database Libraries
Database TypePopular Node.js Client Library
MySQLmysql2, knex
PostgreSQLpg, sequelize
MongoDBmongodb, mongoose
SQLitesqlite3

Basic Steps to Connect to a Database

  • Install the appropriate Node.js database client via npm.
  • Import or require the client in your JavaScript file.
  • Configure the connection with credentials and database info.
  • Establish the connection (usually asynchronous).
  • Perform queries or operations.
  • Close the connection when done.

Example: Connecting to a MySQL Database

This example uses the mysql2 library to connect and query.

📌 Deep Dive: MySQL Connection with mysql2

JAVASCRIPT
const mysql = require('mysql2/promise');

async function connect() {
  const connection = await mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: 'your_password',
    database: 'test_db'
  });

  const [rows] = await connection.execute('SELECT * FROM users');
  console.log(rows);

  await connection.end();
}

connect().catch(console.error);
Output
[{id: 1, name: 'Alice'}, {id: 2, name: 'Bob'}, ...]

💡 Async/Await

Database operations are asynchronous; use async/await or promises to handle them properly.

Example: Connecting to MongoDB

Using the official mongodb Node.js driver to connect:

📌 Deep Dive: MongoDB Connection

JAVASCRIPT
const { MongoClient } = require('mongodb');

async function connect() {
  const uri = 'mongodb://localhost:27017';
  const client = new MongoClient(uri);

  await client.connect();
  const database = client.db('test_db');
  const collection = database.collection('users');

  const users = await collection.find({}).toArray();
  console.log(users);

  await client.close();
}

connect().catch(console.error);
Output
[{_id: ..., name: 'Alice'}, {_id: ..., name: 'Bob'}, ...]

⚠️ Security Warning

Never commit database credentials (usernames, passwords) directly in your source code. Use environment variables or secure config files.

Summary

  • Use Node.js database clients to connect and interact with databases.
  • Connections are asynchronous; handle them with async/await or promises.
  • Each database has specific libraries and connection methods.
  • Always secure your credentials outside of your codebase.