• 카테고리

    질문 & 답변
  • 세부 분야

    풀스택

  • 해결 여부

    미해결

findByIdAndUpdate에 대해 궁금합니다!

21.03.01 23:31 작성 조회수 136

0

router.post("/:id/comments"async(reqresnext=> {
    const newComment = await Comment.create({
        contents: req.body.contents,
        creator: req.body.userId,
        creatorName: req.body.userName,
        post: req.body.id,
        date: moment().format("YYYY-MM-DD hh:mm:ss")
    })
    console.log(newComment"newComment")
    try {
        await Post.findByIdAndUpdate(req.body.id, {
            $push: {
                comments: newComment._id
            }
        })
        await User.findByIdAndUpdate(req.body.userId, {
            $push: {
                comments: {
                    post_id: req.body._id,
                    comment_id: newComment._id
                }
            }
        })
        res.json(newComment)
    } catch (e) {
        console.log(e)
        next(e)
    }
})

좋은 강의 감사합니다 ㅎㅎㅎㅎ

항상 관계형DB, 시퀄라이즈만 사용하다가 처음으로 몽고DB를 사용하고있는데요,

위의 코드에서

await User.findByIdAndUpdate(req.body.userId, {
            $push: {
                comments: {
                    post_id: req.body._id,
                    comment_id: newComment._id
                }
            }
       })

이 부분이

User 테이블에서 req.body.userId에 해당하는 user를 찾은 다음에

User 테이블의 comments컬럼의 post_id, comment_id를 수정한다고 이해하면 되는건가요?

조금 햇갈리네요 ㅠㅠ

그리고 지금 (47) Comment Saga 까지 들었는데

normalRoute/PostWrite.js에서 submit하는 기능이 아직 안되어있는데

이건 다음 강의에서 다루는건가요?

import React, { useState } from "react";
import { useSelectoruseDispatch } from "react-redux";
import {
  Form,
  FormGroup,
  Label,
  Input,
  Button,
  Col,
  Progress,
from "reactstrap";
import { CKEditor } from "@ckeditor/ckeditor5-react";
import ClassicEditor from "@ckeditor/ckeditor5-editor-classic/src/classiceditor";
import { editorConfiguration } from "../../components/editor/EditorConfig";
import Myinit from "../../components/editor/UploadAdapter";
import dotenv from 'dotenv'
dotenv.config()

const PostWrite = () => {
    const {isAuthenticated} = useSelector( (state=> state.auth )
    const [formsetValues] = useState({ title: ""contents: ""fileUrl: "" });
    const dispatch = useDispatch()

    const onChange = (e=> {
      setValues({
        ...form,
        [e.target.name]: e.target.value,
      });
    };

    const getDataFromCKEditor = (eventeditor=> {
        const data = editor.getData()
        console.log(data)
        if(data && data.match("<img src=")) {
          const whereImg_start = data.indexOf("<img src=")
          console.log(whereImg_start)
          let whereImg_end = ""
          let ext_name_find = ""
          let result_Img_Url = ""
          const ext_name = ["jpeg""png""jpg""gif"]

          for(let i=0i<ext_name.lengthi++) {
            if(data.match(ext_name[i])) {
              console.log(data.indexOf(`${ext_name[i]}`))
              ext_name_find = ext_name[i]
              whereImg_end = data.indexOf(`${ext_name[i]}`)
            }
          }
          console.log(ext_name_find)
          console.log(whereImg_end)

          if (ext_name_find === "jpeg") {
            result_Img_Url = data.substring(whereImg_start+10whereImg_end+4
          } else {
            result_Img_Url = data.substring(whereImg_start+10whereImg_end+3)
          }
          console.log(result_Img_Url"result_Img_Url")
          setValues({
            ...form,
            fileUrl: result_Img_Url,
            contents: data
          })
        } else {
          setValues({
            ...form,
            fileUrl: "https://source.unsplash.com/random/301x201",
            // fileUrl: process.env.REACT_APP_BASIC_IMAGE_URL
            contents: data
          })
        }
    }

    const onSubmit = async(e=> {
        await e.preventDefault()
        const { titlecontentsfileUrlcategory } = form
    }

    return (
        <>
          {isAuthenticated ? (
            <Form onSubmit={onSubmit}>
              <FormGroup className="mb-3">
                <Label for="title">Title</Label>
                <Input
                  type="text"
                  name="title"
                  id="title"
                  className="form-control"
                  onChange={onChange}
                />
              </FormGroup>
              <FormGroup className="mb-3">
                <Label for="category">Category</Label>
                <Input
                  type="text"
                  name="category"
                  id="category"
                  className="form-control"
                  onChange={onChange}
                />
              </FormGroup>
              <FormGroup className="mb-3">
                <Label for="content">Content</Label>
                <CKEditor
                  editor={ClassicEditor}
                  config={editorConfiguration}
                  onInit={Myinit}
                  onBlur={getDataFromCKEditor}
                />
                <Button
                  color="success"
                  block
                  className="mt-3 col-md-2 offset-md-10 mb-3"
                >
                  제출하기
                </Button>
              </FormGroup>
            </Form>
          ) : (
            <Col width={50} className="p-5 m-5">
              <Progress animated color="info" value={100} />
            </Col>
          )}
        </>
    );
}

export default PostWrite

47강까지 들은 현재 PostWrite.js인데

게시글을 submit하는 액션이 디스패치 안되어있어서요 ㅎㅎㅎ

등록된 게시글이 없다보니 (42) ~ (45)강의 PostDetail.js의 내용을 확인할 수가 없네요..

답변 1

답변을 작성해보세요.

0

질문1) 네 맞습니다. 굳이 저렇게 해준 이유는 향후 유저를 삭제할때 해당 유저의 comment도 같이 삭제하기 위해서 입니다. 물론 이것은 개발자 취향에 달린거긴한데...

간혹 어떤 사이트는 답글이 남아있어 해당 유저를 클릭해서 정보를 보고 싶을때, 유저가 탈퇴해서 안넘어가지거나 하는 경우가 있습니다. 

저는 유저가 탈퇴하면 해당 게시물도 같이 지워줘야.. 유저가 탈퇴한 목적에 부합하다고 판단하여 로직을 저렇게 만든 것입니다. 

질문2) 종종 submit 부분이 아직 안나온다는 질문을 받습니다... 아마 조금더 들어보시면 있을 것입니다.