Lesson 10-Node.js Database Integration

Node.js with MongoDB Integration

Introduction to MongoDB and Node.js

  • MongoDB: An open-source NoSQL database that stores data in BSON (Binary JSON) format, similar to JSON but with support for additional data types. It is ideal for handling large volumes of unstructured or semi-structured data.
  • Node.js: A JavaScript runtime built on Chrome’s V8 engine, designed for server-side applications and capable of handling high-concurrency requests.

Installing and Configuring MongoDB

Ensure MongoDB is installed on your local machine. Start the MongoDB service with the following command:

mongod --dbpath=/data/db

Verify that Node.js and npm are installed.

Installing the MongoDB Node.js Driver

Install the official MongoDB driver in your Node.js project using npm:

npm install mongodb --save

Connecting to MongoDB

Create a new Node.js file, e.g., app.js, and add the following code to connect to MongoDB:

const MongoClient = require('mongodb').MongoClient;
const uri = "mongodb://localhost:27017/test";
const client = new MongoClient(uri, { useNewUrlParser: true });

client.connect(err => {
  const collection = client.db("test").collection("devices");
  // Perform actions on the collection object
  client.close();
});

CRUD Operations

Insert Data

collection.insertOne({ name: "John", age: 30 }, function(err, res) {
  if (err) throw err;
  console.log("Document inserted");
  client.close();
});

Query Data

collection.find({}).toArray(function(err, result) {
  if (err) throw err;
  console.log(result);
  client.close();
});

Update Data

collection.updateOne({ name: "John" }, { $set: { age: 31 } }, function(err, res) {
  if (err) throw err;
  console.log("Document updated");
  client.close();
});

Delete Data

collection.deleteOne({ name: "John" }, function(err, obj) {
  if (err) throw err;
  console.log("Document deleted");
  client.close();
});

Asynchronous Processing and Error Handling

Since Node.js is asynchronous, database operations require careful handling using callbacks, Promises, or async/await to simplify asynchronous code:

async function main() {
  const client = new MongoClient(uri, { useNewUrlParser: true });
  try {
    await client.connect();
    const db = client.db("test");
    const collection = db.collection("devices");
    const result = await collection.find({}).toArray();
    console.log(result);
  } finally {
    await client.close();
  }
}

main().catch(console.error);

Using Mongoose ORM

Mongoose is an object-oriented model definition library that simplifies MongoDB operations. Install Mongoose:

npm install mongoose --save

Use Mongoose to define models and manipulate data:

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const userSchema = new Schema({
  name: String,
  age: Number
});

const User = mongoose.model('User', userSchema);

mongoose.connect(uri, { useNewUrlParser: true })
  .then(() => {
    const newUser = new User({ name: 'Alice', age: 25 });
    return newUser.save();
  })
  .then(() => {
    console.log('User saved');
    mongoose.connection.close();
  })
  .catch(err => {
    console.error(err);
    mongoose.connection.close();
  });

Node.js with MySQL Integration

Environment Setup

Ensure Node.js and MySQL are installed in your development environment. Node.js can be downloaded from its official website, and MySQL installation guides are available from Oracle’s website.

Installing the MySQL Driver

Use the mysql2 driver for MySQL communication, as it offers better performance and feature support. Install it in your project directory:

npm install mysql2

Creating a Database and Table

Create a database and sample table in MySQL. Log into MySQL and execute:

CREATE DATABASE mydatabase;
USE mydatabase;

CREATE TABLE users (
  id INT AUTO_INCREMENT PRIMARY KEY,
  name VARCHAR(100),
  email VARCHAR(100)
);

Connecting to MySQL

Create a connection to MySQL in your Node.js project:

const mysql = require('mysql2');

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

connection.connect((error) => {
  if (error) throw error;
  console.log('Connected to MySQL database!');
});

Inserting Data

Insert data into the users table using SQL:

const sql = 'INSERT INTO users (name, email) VALUES (?, ?)';
const values = ['John Doe', 'john.doe@example.com'];

connection.query(sql, values, (error, results, fields) => {
  if (error) throw error;
  console.log('Data inserted successfully!');
});

Querying Data

Retrieve all users from the users table:

const sql = 'SELECT * FROM users';

connection.query(sql, (error, results, fields) => {
  if (error) throw error;
  console.log(results);
});

Updating Data

Update a user’s email in the users table:

const sql = 'UPDATE users SET email = ? WHERE id = ?';
const values = ['new.email@example.com', 1];

connection.query(sql, values, (error, results, fields) => {
  if (error) throw error;
  console.log('Data updated successfully!');
});

Deleting Data

Delete a user from the users table:

const sql = 'DELETE FROM users WHERE id = ?';
const values = [1];

connection.query(sql, values, (error, results, fields) => {
  if (error) throw error;
  console.log('Data deleted successfully!');
});

Using Promises and async/await

Use the mysql2 Promise interface for modern, readable code:

const { createConnection } = require('mysql2/promise');

const connection = createConnection({
  host: 'localhost',
  user: 'root',
  password: 'your_password',
  database: 'mydatabase'
});

async function main() {
  try {
    await connection.connect();
    const [rows, fields] = await connection.execute('SELECT * FROM users');
    console.log(rows);
  } catch (error) {
    console.error(error);
  } finally {
    await connection.end();
  }
}

main();

Error Handling

Proper error handling prevents crashes and data corruption:

connection.query(sql, values, (error, results, fields) => {
  if (error) {
    console.error('Error occurred:', error);
  } else {
    console.log('Data processed successfully!');
  }
});

Using Connection Pools

For production environments, connection pools improve performance and resource utilization:

const pool = mysql.createPool({
  host: 'localhost',
  user: 'root',
  password: 'your_password',
  database: 'mydatabase',
  waitForConnections: true,
  connectionLimit: 10,
  queueLimit: 0
});

pool.getConnection((error, connection) => {
  if (error) throw error;
  connection.query(sql, values, (error, results, fields) => {
    if (error) throw error;
    console.log(results);
    connection.release();
  });
});

Using ORM

Object-Relational Mappers (ORMs) like Sequelize or TypeORM provide advanced features like model definitions, relationship management, and transactions. Example using Sequelize:

npm install sequelize

Define a model and manipulate data:

const { Sequelize, DataTypes } = require('sequelize');
const sequelize = new Sequelize('mydatabase', 'root', 'your_password', {
  host: 'localhost',
  dialect: 'mysql'
});

const User = sequelize.define('user', {
  name: DataTypes.STRING,
  email: DataTypes.STRING
}, {
  timestamps: false
});

(async () => {
  await sequelize.authenticate();
  console.log('Connection has been established successfully.');

  await User.sync();

  const user = await User.create({ name: 'Jane Doe', email: 'jane.doe@example.com' });
  console.log(user.toJSON());
})();

Membership Required

You must be a member to access this content.

View Membership Levels

Already a member? Log in here
Share your love