Node.js Database Integration

Using Database Drivers:

Connecting to MongoDB (using the mongodb driver):

                                                    
                                                    const MongoClient = require('mongodb').MongoClient;

// Connection URI
const uri = 'mongodb://localhost:27017/mydatabase';

// Connect to MongoDB
MongoClient.connect(uri, { useNewUrlParser: true, useUnifiedTopology: true })
    .then(client => {
        const db = client.db();
        const collection = db.collection('documents');

        // Perform CRUD operations
        collection.insertOne({ name: 'John' });
        collection.findOne({ name: 'John' });
        collection.updateOne({ name: 'John' }, { $set: { name: 'Jane' } });
        collection.deleteOne({ name: 'Jane' });

        // Close connection
        client.close();
    })
    .catch(err => console.error('Error connecting to MongoDB:', err));

                                                    
                                                

Connecting to MySQL (using the mysql driver):

                                                    
                                                    const mysql = require('mysql');

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

// Connect to MySQL
connection.connect(err => {
    if (err) {
        console.error('Error connecting to MySQL:', err);
        return;
    }
    console.log('Connected to MySQL');

    // Perform CRUD operations
    connection.query('INSERT INTO users (name) VALUES (?)', ['John']);
    connection.query('SELECT * FROM users WHERE name = ?', ['John'], (err, results) => {
        console.log('User:', results[0]);
    });
    connection.query('UPDATE users SET name = ? WHERE name = ?', ['Jane', 'John']);
    connection.query('DELETE FROM users WHERE name = ?', ['Jane']);
});

// Close connection
connection.end();

                                                    
                                                

Connecting to PostgreSQL (using the pg driver):

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

// PostgreSQL connection configuration
const client = new Client({
    user: 'postgres',
    host: 'localhost',
    database: 'mydatabase',
    password: 'password',
    port: 5432,
});

// Connect to PostgreSQL
client.connect()
    .then(() => console.log('Connected to PostgreSQL'))
    .catch(err => console.error('Error connecting to PostgreSQL:', err));

// Perform CRUD operations
client.query('INSERT INTO users (name) VALUES ($1)', ['John']);
client.query('SELECT * FROM users WHERE name = $1', ['John'], (err, result) => {
    console.log('User:', result.rows[0]);
});
client.query('UPDATE users SET name = $1 WHERE name = $2', ['Jane', 'John']);
client.query('DELETE FROM users WHERE name = $1', ['Jane']);

// Close connection
client.end();
                                                    
                                                

Using Object-Relational Mapping (ORM) Libraries:

Connecting to a Database with Sequelize (ORM for various databases):

                                                    
                                                    const { Sequelize, DataTypes } = require('sequelize');

// Database connection configuration
const sequelize = new Sequelize('mydatabase', 'root', 'password', {
    host: 'localhost',
    dialect: 'mysql'
});

// Define a model
const User = sequelize.define('User', {
    name: {
        type: DataTypes.STRING
    }
});

// Perform CRUD operations
(async () => {
    await sequelize.sync();
    const user = await User.create({ name: 'John' });
    console.log('User:', user.toJSON());

    const updatedUser = await User.update({ name: 'Jane' }, { where: { name: 'John' } });
    console.log('Updated User:', updatedUser);

    const deletedUser = await User.destroy({ where: { name: 'Jane' } });
    console.log('Deleted User:', deletedUser);

    // Close connection
    await sequelize.close();
})();
                                                    
                                                

ORM libraries like Sequelize abstract away the underlying SQL queries and provide an object-oriented interface for interacting with databases, making database integration more straightforward and flexible.