교육후 개인공부/React
[Next.js] mongodb에 데이터 삽입하기
뭉지야
2023. 12. 7. 18:52
728x90
글작성기능을 해봤다
그래서 몽고디비에 데이터가 삽입되는 기능을 해봤다.
일단 get과 post기능은 form을 이용하면 쉽게 하기 좋단다
write/page.js
export default function Write() {
return (
<div className="p-20">
<h4>글작성페이지</h4>
{/* get이랑 post하는 방법을 배워보자 */}
<form action="/api/post/new" method="POST">
<input name="title" placeholder="글제목부분" />
<input name="content" placeholder="글내용부분" />
<button type="submit">버튼</button>
</form>
</div>
);
}
pages/api/post/new.js
import { connectDB } from "@/util/database";
export default async function handler(요청, 응답) {
if (요청.method == "POST") {
const client = await connectDB;
const db = client.db("market");
let result = await db.collection("post").insertOne(요청.body);
return 응답.status(200).json("저장완료");
}
}
이렇게 insertOne을 이용하면 mongoDb에 데이터를 삽입하는 기능을 할수있다.
응답과 동시에 페이지 이동하는 기능으로 redirect로 하려면 이렇게 하면된다.
import { connectDB } from "@/util/database";
export default async function handler(요청, 응답) {
if (요청.method == "POST") {
const client = await connectDB;
const db = client.db("market");
let result = await db.collection("post").insertOne(요청.body);
return 응답.redirect(302, "/list");
}
}
728x90