Node.js/Node 이론

Node.js MongoDB와의 통합 예제

P_eli 2023. 12. 11. 15:21
728x90
반응형

Node.js 및 패키지 설치

먼저 Node.js를 설치하고, 프로젝트 폴더를 생성한 후 터미널에서 다음 명령어를 실행하여 필요한 패키지를 설치합니다.

npm init -y
npm install express mongoose ejs body-parser

 

 

프로젝트 구조 설정

프로젝트 폴더에 index.js 파일을 생성하고, views 폴더 안에 index.ejs와 post.ejs 파일을 생성합니다.

 

MongoDB 연결 및 모델 정의

index.js 파일에 MongoDB와의 연결 및 모델 정의를 추가합니다.

 

// index.js

const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');

const app = express();
const port = 3000;

// MongoDB 연결
mongoose.connect('mongodb://localhost:27017/blog', { useNewUrlParser: true, useUnifiedTopology: true });
const db = mongoose.connection;

db.on('error', console.error.bind(console, 'MongoDB connection error:'));
db.once('open', () => {
  console.log('Connected to MongoDB');
});

// 블로그 글 모델 정의
const postSchema = new mongoose.Schema({
  title: String,
  content: String,
  date: { type: Date, default: Date.now }
});

const Post = mongoose.model('Post', postSchema);

// 미들웨어 설정
app.use(bodyParser.urlencoded({ extended: true }));
app.set('view engine', 'ejs');

// 블로그 글 목록 조회
app.get('/', (req, res) => {
  Post.find({}, (err, posts) => {
    if (err) {
      console.error(err);
    } else {
      res.render('index', { posts });
    }
  });
});

// 블로그 글 상세 조회
app.get('/post/:id', (req, res) => {
  const postId = req.params.id;

  Post.findById(postId, (err, post) => {
    if (err) {
      console.error(err);
    } else {
      res.render('post', { post });
    }
  });
});

// 서버 시작
app.listen(port, () => {
  console.log(`Server is running on http://localhost:${port}`);
});

 

 

뷰 파일 작성

views 폴더 안에 index.ejs와 post.ejs 파일을 생성합니다.

<!-- views/index.ejs -->

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Blog</title>
</head>
<body>
  <h1>Blog</h1>
  <ul>
    <% posts.forEach(post => { %>
      <li><a href="/post/<%= post._id %>"><%= post.title %></a></li>
    <% }); %>
  </ul>
</body>
</html>

 

 

실행

터미널에서 다음 명령어를 실행하여 서버를 시작합니다.

 

node index.js

 

브라우저에서 http://localhost:3000으로 이동하여 간단한 블로그를 확인할 수 있습니다. 글 목록과 글 상세보기 페이지가 나타납니다.

728x90
반응형