본문 바로가기

Learn/Next.js

Next.js (5)

 

 오늘은 DELETE

 

 기존에 해왔던것들과 마찬가지로 서버로 보내고 그걸 다시 DB에 저장시키는 방식인데

이번에는 server 컴포넌트가 아닌 클라이언트 컴포넌트로 만들어서 보다 유용하게 만들었다.

 

'use client'

요렇게 클라이언트컴포넌트를 시작하고

 

useEffect 를 사용하지 않고 props로 내려줬다.

export default function ListItem ({result}){

    // useEffect(()=>{
    //     //서버에 부탁해서 DB게시물 가져옴
    //     // result = DB게시물
    // },[])
    //단점 : 검색노출 어려움 -> useEffect 실행이 제일 마지막이라
    return (
        <div>
            {result.map((el,idx)=>{
            return(
                <div className="list-item" key={idx}>
                    <Link prefetch={false} href={`/detail/${el._id}`}>
                        <h4>{el.title}</h4>
                    </Link>
                    <Link href={`/edit/${el._id}`}>수정</Link>
                    <p>{el.content}</p>
                    <span onClick={()=>{
                        fetch('/api/post/delete', {method : 'DELETE', body : el._id})
                    }}>삭제</span>
                </div>
                )
        })}
        </div>
    )

}

 

그리고 api 주소에 맞게 server도 만들고

 

import { connectDB } from "@/util/database"
import { ObjectId } from "mongodb";

export default async function handler(res, req){
    if (res.method === 'DELETE'){
        let db = (await connectDB).db('forum')
        let result = db.collection('post').deleteOne({_id : new ObjectId(res.body._id)})
    }
  req.redirect(302, '/list')
}

deleteOne() 메소드로 삭제 요청하면 끝!

 

공식사이트

https://www.mongodb.com/docs/manual/reference/method/db.collection.deleteOne/

 

db.collection.deleteOne() — MongoDB Manual

Docs Home → MongoDB Manual db.collection.deleteOne()mongosh MethodThis page documents a mongosh method. This is not the documentation for database commands or language-specific drivers, such as Node.js.For the database command, see the delete command.For

www.mongodb.com

 

 

'Learn > Next.js' 카테고리의 다른 글

Next.js (7) 로그인 방식 정리 및 OAuth 기능 구현  (0) 2023.07.09
Next.js (6) static/dynamic rendering/캐싱  (0) 2023.07.08
Next.js 프로젝트(4)  (0) 2023.07.05
Next.js 프로젝트 (3)  (0) 2023.07.04
Next.js 프로젝트 (2)  (0) 2023.07.03