const result = await db
.collection("post")
.findOne({ _id: new ObjectId("64880201097b4e89b21843f3") });
findOne()์์ object ์๋ฃ๋ฅผ ๋ฃ์ผ๋ฉด ๊ทธ ๋ด์ฉ์ด ํฌํจ๋ document ํ๋๋ฅผ ๊ฐ์ ธ๋ค์ค๋๋ค.
ObjectID import ํด์์ผํฉ๋๋ค.
console.log(props) ํ๋ฉด
{ params: { id: '1' }, searchParams: {} } ์ถ๋ ฅ๋ฉ๋๋ค.
"use client";
import { useRouter } from "next/navigation";
export default function DetailLink() {
const router = useRouter();
return (
<button
onClick={() => {
router.push("/");
}}
>
๋ฒํผ
</button>
);
}
- push : ํ์ด์ง ์ด๋
- back : ๋ค๋ก๊ฐ๊ธฐ
- forward : ์์ผ๋ก๊ฐ๊ธฐ
- refresh : ๋ฐ๋๋ด์ฉ๋ง ์๋ก๊ณ ์นจ(soft refresh)
- prefetch : ํ์ด์ง ๋ฏธ๋ฆฌ๋ก๋ (url์ ๋ด์ฉ์ ๋ฏธ๋ฆฌ ๋ก๋ํด์ค๋๋ค.)
Link ํ๊ทธ์๋ prefetch ๊ธฐ๋ฅ ๋ด์ฅ๋์ด ์์ต๋๋ค.
prefetch ๊ธฐ๋ฅ ๋๊ณ ์ถ์ผ๋ฉด prefetch ์์ฑ์ false๋ก ํ๋ฉด ๋ฉ๋๋ค.
<Link prefetch={false} href={`/detail/${data._id}`}>
- usePathname() : ํ์ฌ URL ์ถ๋ ฅ
- useSearchParams() : Search parameter(query string) ์ถ๋ ฅ
- useParams() : dynamic route์ ์ ๋ ฅํ ๋ด์ฉ
ex) /pages/api/test.js
import { connectDB } from "@/util/database";
export default async function handler(req, res) {
const db = (await connectDB).db("forum");
const result = await db.collection("post").find().toArray();
if (req.method === "GET") {
return res.status(200).json(result);
}
}
<form action="/api/post/new" method="POST">
<input name="title" placeholder="๊ธ์ ๋ชฉ" />
<input name="content" placeholder="๊ธ๋ด์ฉ" />
<button>๋ฒํผ</button>
</form>
action์๋ URL ๊ธฐ์ , method๋ GET, POST ์ค์ ํ๋ ๊ธฐ์
๊ทธ URL๊ณผ method๋ก ๋ง๋ค์ด๋์ ์๋ฒ๊ธฐ๋ฅ์ input์ ์ ํ ๋ด์ฉ๋ค์ ์ ๋ฌํด์ค๋๋ค.
req.body : ํผ์ผ๋ก ์ ์กํ ๋ฐ์ดํฐ
{ title : "์๋
", content : "๋ฐ๊ฐ์" }
import { connectDB } from "@/util/database";
export default async function handler(req, res) {
if (req.method === "POST") {
if (req.body.title === "" || req.body.content === "")
return res.status(500).json("๋ด์ฉ์ ๋ชจ๋ ์ ์ด์ฃผ์ธ์.");
try {
const db = (await connectDB).db("forum");
const result = await db.collection("post").insertOne(req.body);
return res.redirect(302, "/list");
} catch (error) {
return res.status(400).json("Error");
}
}
}