비동기 데이터베이스 처리 MongoDB, MySQL에서 Async/Await 활용하기

1. 비동기 데이터베이스 처리가 중요한 이유

웹 애플리케이션에서 데이터베이스(DB)는 필수적인 요소이며, 비동기 프로그래밍을 활용하면 성능을 최적화하고 응답 속도를 향상시킬 수 있다. Node.js 환경에서는 MongoDB(Mongoose)와 MySQL(mysql2) 같은 데이터베이스를 비동기적으로 다룰 수 있다.

이번 포스트에서는 MongoDB와 MySQL에서 Async/Await을 활용한 비동기 데이터베이스 처리 방법을 다룬다.


2. MongoDB에서 Async/Await을 활용한 데이터 처리

2.1 MongoDB 연결 설정

MongoDB는 NoSQL 데이터베이스로, JSON 기반의 문서(Document) 형태로 데이터를 저장한다. Node.js에서는 mongoose 라이브러리를 사용하여 데이터베이스와 비동기적으로 통신할 수 있다.

mongoose 설치

npm install mongoose

✅ MongoDB 연결 예제 (Async/Await 활용)

const mongoose = require("mongoose");

async function connectDB() {
    try {
        await mongoose.connect("mongodb://localhost:27017/mydatabase", {
            useNewUrlParser: true,
            useUnifiedTopology: true,
        });
        console.log("MongoDB 연결 성공");
    } catch (error) {
        console.error("MongoDB 연결 실패:", error);
    }
}

connectDB();

2.2 MongoDB에서 데이터 생성(Create)

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

const User = mongoose.model("User", UserSchema);

async function createUser() {
    try {
        const newUser = new User({ name: "철수", email: "chulsoo@example.com", age: 25 });
        await newUser.save();
        console.log("사용자 생성 완료:", newUser);
    } catch (error) {
        console.error("사용자 생성 오류:", error);
    }
}

createUser();

2.3 MongoDB에서 데이터 조회(Read)

async function getUsers() {
    try {
        const users = await User.find();
        console.log("사용자 목록:", users);
    } catch (error) {
        console.error("사용자 조회 오류:", error);
    }
}

getUsers();

2.4 MongoDB에서 데이터 업데이트(Update)

async function updateUser(userId) {
    try {
        const updatedUser = await User.findByIdAndUpdate(userId, { age: 30 }, { new: true });
        console.log("업데이트된 사용자:", updatedUser);
    } catch (error) {
        console.error("사용자 업데이트 오류:", error);
    }
}

updateUser("사용자_아이디");

2.5 MongoDB에서 데이터 삭제(Delete)

async function deleteUser(userId) {
    try {
        await User.findByIdAndDelete(userId);
        console.log("사용자 삭제 완료");
    } catch (error) {
        console.error("사용자 삭제 오류:", error);
    }
}

deleteUser("사용자_아이디");

3. MySQL에서 Async/Await을 활용한 데이터 처리

3.1 MySQL 연결 설정

MySQL은 **관계형 데이터베이스(RDBMS)**로, mysql2 라이브러리를 사용하여 비동기 쿼리를 실행할 수 있다.

mysql2 설치

npm install mysql2

✅ MySQL 연결 예제 (Async/Await 활용)

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

async function connectDB() {
    try {
        const connection = await mysql.createConnection({
            host: "localhost",
            user: "root",
            password: "password",
            database: "mydatabase",
        });
        console.log("MySQL 연결 성공");
        return connection;
    } catch (error) {
        console.error("MySQL 연결 실패:", error);
    }
}

3.2 MySQL에서 데이터 생성(Create)

async function createUser() {
    const connection = await connectDB();
    const sql = "INSERT INTO users (name, email, age) VALUES (?, ?, ?)";
    const values = ["영희", "younghee@example.com", 28];
    await connection.execute(sql, values);
    console.log("사용자 생성 완료");
}

createUser();

3.3 MySQL에서 데이터 조회(Read)

async function getUsers() {
    const connection = await connectDB();
    const [rows] = await connection.execute("SELECT * FROM users");
    console.log("사용자 목록:", rows);
}

getUsers();

3.4 MySQL에서 데이터 업데이트(Update)

async function updateUser(userId) {
    const connection = await connectDB();
    const sql = "UPDATE users SET age = ? WHERE id = ?";
    const values = [35, userId];
    await connection.execute(sql, values);
    console.log("사용자 업데이트 완료");
}

updateUser(1);

3.5 MySQL에서 데이터 삭제(Delete)

async function deleteUser(userId) {
    const connection = await connectDB();
    const sql = "DELETE FROM users WHERE id = ?";
    await connection.execute(sql, [userId]);
    console.log("사용자 삭제 완료");
}

deleteUser(1);

4. 결론

  • MongoDB는 NoSQL 방식으로 유연한 데이터 저장이 가능하며, mongoose를 사용하여 비동기적으로 처리할 수 있다.
  • **MySQL은 관계형 데이터베이스(RDBMS)**로, mysql2를 활용하여 Async/Await을 적용할 수 있다.
  • 비동기 데이터베이스 처리를 활용하면 성능을 향상시키고, 응답 속도를 최적화할 수 있다.

이제 MongoDB와 MySQL 중 프로젝트에 맞는 데이터베이스를 선택하고, 효율적으로 비동기 처리를 적용해 보자!

Leave a Comment