게시글을 수정하려고 한다
생성과 크게 다르지 않으므로 자세한 설명은 생략한다
// edit/page.js
import { connectDB } from '@/util/database';
import { ObjectId } from 'mongodb';
export default async function Edit(props) {
const db = (await connectDB).db('forum');
const item = await db
.collection('post')
.findOne({ _id: new ObjectId(props.params.id) });
return (
<div>
<h4>글 수정</h4>
<form action="/api/post/edit" method="POST">
<div className="flex flex-col items-start gap-4 mt-4 pt-4 border-t border-gray-300">
<input type="hidden" name="_id" defaultValue={item?._id} />
<input
type="text"
name="title"
className="text-black"
placeholder="title"
defaultValue={item?.title}
/>
<textarea
name="content"
className="text-black"
placeholder="content"
defaultValue={item?.content}
></textarea>
</div>
<button type="submit" className="mt-2">
Edit
</button>
</form>
</div>
);
}
해당 게시글의 title, content를 가져와 defaultValue로 설정해주고
<input>
을 하나 더 만들어 type="hidden"
으로 설정하여 수정 시 필요한 _id값 도 같이 전달해준다
// api/post/edit.js
import { connectDB } from '@/util/database';
import { ObjectId } from 'mongodb';
export default async function handler(req, res) {
if (req.method === 'POST') {
const db = (await connectDB).db('forum');
const { _id, ...post } = req.body;
if (!req.body.title || !req.body.content) {
return res.status(500).json('title or content is empty');
}
try {
await db.collection('post').updateOne(
{ _id: new ObjectId(_id) },
{
$set: post, // $set : 내용 덮어쓰기
$currentDate: { lastModified: true },
},
);
res.redirect(302, `/detail/${req.body._id}`);
} catch (error) {
console.error(error);
}
}
}
updateOne()
의 다른 속성들이 궁금하다면 이 글을 참고하면 된다
이번 글에서는 method를 POST로 보내고 API에서 게시글을 수정하는 로직으로 처리를 해줬다
Ajax를 사용하고 싶을 경우, 이후 작성해 놓은 이 게시글 을 참고하면 좋을 듯하다