HTML + CSS + JavaScript + Node + MongoDB 기반 프로젝트 시작
1. 파일 생성한다.
2. npm init -y 패키지 설치한다.
3. npm i express 설치
4. npm i ejs 템플릿 엔진 모듈 설치
5. npm i mongoose --save 몽구스 설치
3번, 4번, 5번 한꺼번에 설치 express + mongoose + ejs ( npm i express mongoose ejs )
6. app.js 파일 생성 (=index.js)
7. 기본 라우트 작성하기 위해 app.js 파일에서 아래의 코드 작성
const express = require("express");
const app = express();
app.get("/", (req, res) => {
console.log("성공");
res.send("기본 라우트 성공");
});
app.listen("3000", () => {
console.log("3000 port 성공");
console.log("http://localhost:3000/");
});
8. path 모듈 코드 작성
const path = require("path"); // path 모듈
app.set("view engine", "ejs");
app.set("views", path.join(__dirname, "views"));
9. home.ejs 파일 생성하고 html 코드 작성
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Home</title>
</head>
<body>
<h1>홈페이지</h1>
</body>
</html>
10. res.render("home"); 코드 작성하고 서버 실행하기
app.get("/", (req, res) => {
res.render("home");
});
11. campground.js 파일 생성하여 스키마와 모델 작성
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const CampgroundSchema = new Schema({
title: String,
price: String,
description: String,
location: String,
});
module.exports = mongoose.model("Campground", CampgroundSchema);
12. 데이터베이스 연결하기 위해서 app.js 파일에서 아래의 코드 작성
const mongoose = require("mongoose");
main().then(() => console.log("성공?"));
main().catch((err) => console.log(err));
async function main() {
mongoose.set("strictQuery", true);
await mongoose.connect("mongodb://localhost:27017/yelp-camp");
}
13. app.js 파일에서 아래의 코드 작성
const Campground = require("./models/campground");
app.get("/makecampground", async (req, res) => {
const camp = new Campground({
title: "My Backyard",
description: "cheap camping",
});
await camp.save();
res.send(camp);
});
13-1.몽고DB 쉘에서 데이터베이스 연결 확인하고 URL : /makecampground 접속하기
14. 데이터베이스 seed
https://github.com/wangkodok/web-development-camp/commit/61a6c5700d649574fe462c5d3e3e48d27848913d#diff-748df92e52ea66161a96a3042ff9535605d39e489d3a949b950f99f9a103e27e
데이터베이스 seed · wangkodok/web-development-camp@61a6c57
wangkodok committed Nov 30, 2023
github.com
15. index.ejs 라우트
app.get("/campgrounds", async (req, res) => {
const campgrounds = await Campground.find({});
res.render("campgrounds/index", { campgrounds });
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>campgrounds</title>
</head>
<body>
<h1>all campgrounds</h1>
<ul>
<% for(let campground of campgrounds) {%>
<li><%= campground.title %></li>
<% } %>
</ul>
</body>
</html>
16. show 라우트 및 파라미터 받아와서 상세 페이지로 이동
app.get("/campgrounds/:id", async (req, res) => {
const campground = await Campground.findById(req.params.id);
res.render("campgrounds/show", { campground });
});
<!-- 파라미터 받아와서 상세 페이지로 이동 -->
<ul>
<% for(let campground of campgrounds) {%>
<li>
<a href="/campgrounds/<%= campground._id %>"><%= campground.title %></a>
</li>
<% } %>
</ul>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>show</title>
</head>
<body>
<h1><%= campground.title %></h1>
<h2><%= campground.location %></h2>
</body>
</html>
17. new.ejs 라우트 및 데이터베이스에 데이터 추가 (생략된 코드는 깃허브에서 확인)
app.use(express.urlencoded({ extended: true }));
app.get("/campgrounds/new", (req, res) => {
res.render("campgrounds/new");
});
app.post("/campgrounds", async (req, res) => {
const campground = new Campground(req.body.campground);
await campground.save();
res.redirect(`/campgrounds/${campground._id}`);
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>new</title>
</head>
<body>
<form action="/campgrounds" method="post">
<div>
<label for="title">title</label>
<input type="text" id="title" name="campground[title]" />
</div>
<div>
<label for="location">location</label>
<input type="text" id="location" name="campground[location]" />
</div>
<button>add campground</button>
</form>
<a href="/campgrounds">all campgrounds</a>
</body>
</html>
18. edit.ejs 라우트 및 편집하고 업데이트 (생략된 코드는 깃허브에서 확인)
const methodOverride = require("method-override");
app.use(methodOverride("_method"));
app.get("/campgrounds/:id/edit", async (req, res) => {
const campground = await Campground.findById(req.params.id);
res.render("campgrounds/edit", { campground });
});
app.put("/campgrounds/:id", async (req, res) => {
const { id } = req.params;
const campground = await Campground.findByIdAndUpdate(id, {
...req.body.campground,
});
res.redirect(`/campgrounds/${campground._id}`);
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>edit</title>
</head>
<body>
<h1>edit campground</h1>
<form action="/campgrounds/<%= campground._id %>?_method=PUT" method="post">
<div>
<label for="title">title</label>
<input
type="text"
id="title"
name="campground[title]"
value="<%= campground.title %>"
/>
</div>
<div>
<label for="location">location</label>
<input
type="text"
id="location"
name="campground[location]"
value="<%= campground.location %>"
/>
</div>
<button>update campground</button>
</form>
<a href="/campgrounds/<%= campground._id %>">back to campground</a>
</body>
</html>
19. 데이터 삭제
app.delete("/campgrounds/:id", async (req, res) => {
const { id } = req.params;
await Campground.findByIdAndDelete(id);
res.redirect("/campgrounds");
});
<form action="/campgrounds/<%= campground._id %>?_method=DELETE" method="post">
<button>delete</button>
</form>
CRUD 기능을 살펴봤습니다. 정리를 하자면 Create로 데이터를 생성하고 Read로 데이터를 읽으며 Update로 새로운 데이터를 업데이트하고 Delete로 데이터를 삭제하는 것이다.
클라이언트 / 서버간 HTTP 프로토콜을 이용해 RESTful하게 데이터를 전송할 때도 CRUD 개념이 활용된다.