</>
Skip to content
Node.js lessons (38/44)

Node.js — Database

Database Options

DatabasePackageType
MySQLmysql2SQL
PostgreSQLpgSQL
MongoDBmongooseNoSQL
SQLitesqlite3SQL

MySQL Connection

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

async function connect() {
    const connection = await mysql.createConnection({
        host: 'localhost',
        user: 'root',
        password: 'password',
        database: 'mydb'
    });
    
    const [rows] = await connection.execute('SELECT * FROM users');
    console.log(rows);
    
    await connection.end();
}

PostgreSQL Connection

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

const client = new Client({
    host: 'localhost',
    user: 'postgres',
    password: 'password',
    database: 'mydb'
});

await client.connect();
const res = await client.query('SELECT * FROM users');
console.log(res.rows);
await client.end();

MongoDB Connection

const mongoose = require('mongoose');

mongoose.connect('mongodb://localhost/mydb');

const userSchema = new mongoose.Schema({
    name: String,
    email: String
});

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

Mini Practice

  1. Connect to MySQL
  2. Connect to PostgreSQL
  3. Connect to MongoDB
  4. Perform basic CRUD operations

Up Next

Continue with MySQL — MySQL integration.

Related Topics

Frequently Asked Questions about Database

What is Database in Node.js?

Database is a fundamental concept in Node.js. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn Database?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Database.

Why is Database important in Node.js?

Database is essential for Node.js development. Understanding this concept will help you write better code and solve real-world problems more effectively.