본문 바로가기
Frontend/Project(개인 기록용)

firebase와 redux로 구현한 mongoDB(유저정보)와 게시글 연동

by Johnny_gon 2023. 6. 6.
728x90
반응형

 

 

redux store에 저장 되어 있는 정보를 useSelector로 가져온 뒤에

firebase에서 부여하는 고유의 uid를 찾아서 server단으로 body에 추가하여 보내줍니다.

 
   const user = useSelector((state) => state.user);
 
   const onSubmit = (e) => {
    e.preventDefault();
    if (title === "") {
      return (titleRef.current.placeholder = "빈 칸 확인해주세요");
    } else if (content === "") {
      return (contentRef.current.placeholder = "빈 칸 확인해주세요");
    }

    let body = {
      title: title,
      content: content,
      image: image,
      //uid firebase에서 부여하는 유저의 고유 id
      uid: user.uid,
    };
 
    axios
      .post("/api/post/submit", body)
      .then((res) => {
        if (res.data.success) {
          alert("글 작성이 완료되었습니다.✔");
          navigate("/");
        } else {
          alert("글 작성이 실패하였습니다.❌");
        }
      })
      .catch((err) => {
        console.log(err);
      });
    };
 

 

 

server 코드(Post스키마 수정)

 
  const mongoose = require("mongoose");
 
  const postSchema = new mongoose.Schema(
    {
      title: String,
      content: String,
      postNum: Number,
      image: String,
      author: {
      //ObjectId를 type으로 주게 되면 
      //같은 ObjectId의 User doc에 있는 모든 정보가 들어옵니다.
        type: mongoose.Schema.Types.ObjectId,
        ref: "User",
      },
    },
    { collection: "posts" }
  );
  const Post = mongoose.model("Post", postSchema);
 
  module.exports = { Post };
 

 

 

 

글을 업로드할 때 uid를 보내주기 때문에  mongoDB user정보에서

uid가 같은 doc를 찾아서 id값을 author로 넘겨줍니다. (아래 코드 참조)

 
   router.post("/submit", (req, res) => {
 
     let temp = {
       title: req.body.title,
       content: req.body.content,
       image: req.body.image,
     };
     //Counet에서 name이 counter것을 찾아서
     Counter.findOne({ name: "counter" })
       .exec()
       .then((counter) => {
         //postNum을 새로 부여해 주고
         temp.postNum = counter.postNum;
        //User에서 uid값을 찾아서
         User.findOne({ uid: req.body.uid })
           .exec()
           .then((userInfo) => {
            //_id를 author로 넣음
             temp.author = userInfo._id;
             const CommunityPost = new Post(temp);
             CommunityPost.save().then(() => {
               //counter 1증가
               Counter.updateOne(
                 { name: "counter" },
                 { $inc: { postNum: 1 } }
               ).then(() => {
                 res.status(200).json({ success: true });
               });
             });
           });
       })
       .catch((err) => {
         res.status(400).json({ success: false });
         console.log(err);
       });
   });
 

 

 

 

 mongoDB에서 확인을 해보면 user의 _id(mongoDB고유 id)와 아래 post정보의 author id와 같은 것을 알 수 있습니다.

 

user 정보

 

post 정보

 

 

 

 

유저정보가 필요한 list와 detail 페이지에 보내주기 위한 작업

 
   router.post("/list", (req, res) => {
   
     //몽고DB에서 doc찾는 방법은 find()
     Post.find()
       .populate("author")
       .exec()
       .then((doc) => {
         //응답으로 postList: doc로  client쪽으로 보내줍니다.
         res.status(200).json({ success: true, postList: doc });
       })
       .catch((err) => {
         res.status(400).json({ success: false });
         console.log(err);
       });
   });
   router.post("/detail", (req, res) => {
     // console.log(req.body.postNum); //post id 출력
     // 스트링으로 넘어오기때문에 Number로 감싸줍니다
     Post.findOne({ postNum: Number(req.body.postNum) })
       .populate("author")
       .exec()
       .then((doc) => {
         // console.log(doc);
         res.status(200).json({ success: true, post: doc });
       })
       .catch((err) => {
         res.status(400).json({ success: false });
         console.log(err);
       });
   });
 

 

 

 

client list detail페이지에서 콘솔을 찍어 보면 _id로 추적하여 포함시킨 author 정보가 잘 들어가 있는 것을 확인할 수 있습니다.

 

 

 

 

 

client 코드

 

useSeleter()를 통해서 현재 어떤 유저가 접속했는지

접속한 유저 uid와 글의 uid가 같으면 수정,삭제 가능하게

다르다면 수정,삭제 버튼 숨기기 구현

 
   {user.uid === props.postDetil.author.uid && (
        <BtnDiv>
          <Link to={`/edit/${props.postDetil.postNum}`}>
            <button className="edit">수정</button>
          </Link>
          <Link>
            <button onClick={deleteHandler} className="delete">
              삭제
            </button>
          </Link>
        </BtnDiv>
      )}
 

 

 

참조  https://www.zerocho.com/category/MongoDB/post/59a66f8372262500184b5363

 

(MongoDB) Mongoose(몽구스) populate

안녕하세요. 이번 시간에는 몽구스의 편리한 기능 중 하나인 populate에 대해 알아보겠습니다. 몽고DB를 사용하다보면 하나의 다큐먼트가 다른 다큐먼트의 ObjectId를 쓰는 경우가 있습니다. 그럴 때

www.zerocho.com

 

728x90
반응형