/app/edit/[id]/page.js
이 코드는 수정페이지에 대한 코드입니다.
import { connectDB } from "@/util/database"
import { ObjectId } from "mongodb"
export default async function Edit(props){
const db=(await connectDB).db("forum")
//db에 있는 글 하나를 가져오고 싶을때 -> findOne()
let result= await db.collection('post').findOne({ _id:new ObjectId(props.params.id)})
//db에 있는 글 하나를 수정하고 싶을때
console.log(result)
return(
<>
<h3>글 수정</h3>
<form action="/api/post/fix" method="POST">
<input name="title" defaultValue={result.title}></input> {/* value=> input에 미리 입력된 값 */}
<input name="content" defaultValue={result.content}/>
<input name="id" style={{display:'none'}} defaultValue={result._id.toString()} /> {/* 서버한테 보낼 수정하고 싶은 글의 id*/}
<button type="submit">버튼</button>
</form>
</>
)
}
/api/post/fix.js
import { connectDB } from "@/util/database"
import { ObjectId } from "mongodb"
export default async function handler(req,res){
if(req.method=='POST'){
// console.log("hi",req.body)
let change= {title:req.body.title,content:req.body.content}
//수정할때도 바뀐내용이 없다면 기존 값 그대로.
// 바꼈다면 바뀐내용으로 수정되도록.
const db=(await connectDB).db('forum')
// //이때 수정해야할 도큐먼트가 뭔지 사용자가 서버한테 전달을 해야함.서버는 수많은 글 중에서 어떤 거를 수정해야하는지 모르니까.
let result= await db.collection('post').updateOne({_id:new ObjectId(req.body._id)},{$set:change})
console.log('res',result)
res.status(200).redirect(302,'/list')
}
}
여기서 새로운 값으로 수정하려면 그 새로입력한 내용으로 수정이 되어야하는데..아무리해도 안되고 있습니다..
맨처음에 입력했던 그 값 그대로예요 ㅠㅠ