MongoDB는 NoSQL 데이터베이스로서 Node.js와 함께 사용되면 강력한 웹 애플리케이션을 구축하는 데 매우 유용합니다. Node.js의 Express 프레임워크를 사용하여 MongoDB와의 연동 및 CRUD(Create, Read, Update, Delete) 작업을 수행하는 간단한 예제를 살펴보겠습니다.
1. 프로젝트 설정
먼저 프로젝트 폴더를 만들고 다음 명령을 사용하여 Express 및 MongoDB 모듈을 설치합니다.
npm init -y
npm install express mongodb
2. 코드 작성
다음은 Express 앱과 MongoDB를 연결하고 CRUD 작업을 수행하는 코드입니다.
const express = require('express');
const { MongoClient, ObjectId } = require('mongodb');
const app = express();
const PORT = process.env.PORT || 3000;
const MONGO_URL = 'mongodb://localhost:27017'; // MongoDB 접속 주소
const DB_NAME = 'mydb'; // 사용할 데이터베이스 이름
const COLLECTION_NAME = 'users'; // 사용자 컬렉션 이름
// MongoDB 클라이언트 생성
const client = new MongoClient(MONGO_URL, { useUnifiedTopology: true });
// Express 미들웨어
app.use(express.json());
// 서버 시작
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
// MongoDB에 연결
client.connect((err) => {
if (err) {
console.error('Failed to connect to MongoDB:', err);
return;
}
console.log('Connected to MongoDB');
});
});
// 사용자 생성 (Create)
app.post('/users', async (req, res) => {
const newUser = req.body; // 요청 본문에서 새 사용자 정보 가져오기
const db = client.db(DB_NAME); // 데이터베이스 가져오기
const collection = db.collection(COLLECTION_NAME); // 컬렉션 가져오기
try {
const result = await collection.insertOne(newUser); // 사용자 추가
res.json(result.ops[0]); // 추가된 사용자 정보 응답
} catch (err) {
console.error('Error creating user:', err);
res.status(500).json({ error: 'Failed to create user' });
}
});
// 사용자 조회 (Read)
app.get('/users', async (req, res) => {
const db = client.db(DB_NAME);
const collection = db.collection(COLLECTION_NAME);
try {
const users = await collection.find().toArray(); // 모든 사용자 조회
res.json(users); // 조회된 사용자 목록 응답
} catch (err) {
console.error('Error fetching users:', err);
res.status(500).json({ error: 'Failed to fetch users' });
}
});
// 사용자 업데이트 (Update)
app.put('/users/:id', async (req, res) => {
const userId = req.params.id; // 요청 URL에서 사용자 ID 가져오기
const updatedUser = req.body; // 요청 본문에서 업데이트된 사용자 정보 가져오기
const db = client.db(DB_NAME);
const collection = db.collection(COLLECTION_NAME);
try {
const result = await collection.updateOne(
{ _id: ObjectId(userId) }, // 해당 ID를 가진 사용자를 찾음
{ $set: updatedUser } // 업데이트할 사용자 정보 설정
);
res.json(result.modifiedCount); // 업데이트된 문서 수 응답
} catch (err) {
console.error('Error updating user:', err);
res.status(500).json({ error: 'Failed to update user' });
}
});
// 사용자 삭제 (Delete)
app.delete('/users/:id', async (req, res) => {
const userId = req.params.id;
const db = client.db(DB_NAME);
const collection = db.collection(COLLECTION_NAME);
try {
const result = await collection.deleteOne({ _id: ObjectId(userId) }); // 해당 ID를 가진 사용자 삭제
res.json(result.deletedCount); // 삭제된 문서 수 응답
} catch (err) {
console.error('Error deleting user:', err);
res.status(500).json({ error: 'Failed to delete user' });
}
});
3. CRUD 작업 수행
위 코드에서는 다음과 같은 CRUD 작업을 수행합니다.