Database Connectivity in Express.js: Connecting to MongoDB and MySQL

Integrating your Express.js application with a database is a crucial step in building dynamic and data-driven web applications. This guide will take you through the process of establishing a connection between your Express.js app and databases like MongoDB and MySQL, enabling you to efficiently store and retrieve data.

Connecting to MongoDB

Install MongoDB Driver: Begin by installing the MongoDB driver for Node.js using npm.

npm install mongodb

Create Connection: In your Express.js application, establish a connection to your MongoDB database.

const MongoClient = require('mongodb').MongoClient;
const url = 'mongodb://localhost:27017/mydb';

MongoClient.connect(url, (err, client) => {
  if (err) throw err;
  const db = client.db('mydb');
  // Perform database operations
  client.close();
});

Connecting to MySQL

Install MySQL Driver: Install the MySQL driver for Node.js using npm.

npm install mysql

Create Connection: Connect your Express.js app to your MySQL database.

const mysql = require('mysql');
const connection = mysql.createConnection({
  host: 'localhost',
  user: 'root',
  password: 'password',
  database: 'mydb'
});

connection.connect((err) => {
  if (err) throw err;
  // Perform database operations
  connection.end();
});

Performing Database Operations

Insert Data: Use appropriate methods to insert data into your database.

// MongoDB
db.collection('users').insertOne({ name: 'John', age: 30 });

// MySQL
const sql = 'INSERT INTO users (name, age) VALUES (?, ?)';
connection.query(sql, ['John', 30], (err, result) => {
  if (err) throw err;
  console.log('Record inserted: ' + result.affectedRows);
});

Retrieve Data: Fetch data from your database.

// MongoDB
db.collection('users').find({}).toArray((err, result) => {
  if (err) throw err;
  console.log(result);
});

// MySQL
const sql = 'SELECT * FROM users';
connection.query(sql, (err, result) => {
  if (err) throw err;
  console.log(result);
});

 

Conclusion

Connecting your Express.js application to databases like MongoDB or MySQL unlocks the potential for efficient data storage and management. By following these steps, you'll be well-equipped to create web applications that seamlessly interact with databases, allowing you to deliver robust, data-driven experiences to your users.