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

글 작성 데이터마다 숫자 부여하기

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

 

글 작성한 데이터의 수정,삭제 작업를 위해 

작성글마다 고유의 number를 부여해줍니다..

 

 

server 코드

새로운 스키마 추가(counter)

 
  const mongoose = require("mongoose");
 
  const counterSchema = new mongoose.Schema(
    {
      name: String,
      postNum: Number,
    },
    { collection: "counter" }
  );
 
  const Counter = mongoose.model("counter", counterSchema);
 
  module.exports = { Counter };
 

 

 

기존 Post스키마에도 postNum : Number를 추가하고 몽고DB에서 확인하면

새로운 스키마가 추가된 것을 확인할 수 있습니다.

 

 

 

그리고 위에 counter스키마에서 설정했던 형식(num은 int)으로 데이터를 하나 만들어줍니다.

 

 

 

만들고 server 메인 페이지의 submit 부분을 수정해 줍니다.

 
  app.post("/api/post/submit", (req, res) => {
    //req.body는 client Upload에서 요청온 title,content data
    let temp = req.body;
    //Counter스키마에서 이름counter를 찾아서
    Counter.find({ name: "counter" })
      .exec()
      .then((counter) => {
        //temp.postNum에 방금 찾은 counter.postNum을 넣어줍니다..
        temp.postNum = counter.postNum;
        const TestPost = new Post(temp);
 
        TestPost.save().then(() => {
          //updateOne({ 찾을 doc },{어떻게 업데이트 시킬지})
          Counter.updateOne({ name: "counter" }, { $inc: { postNum: 1 } }).then(
            () => {
              res.status(200).json({ success: true, text: "DB저장 완료" });
            }
          );
        });
      })
      .catch((err) => {
        res.status(400).json({ success: false, text: "DB저장 실패" });
      });
  });
 

 

 

 

 

이렇게 해주고 페이지 열어서 글 업로드 이후에 몽고 DB에서 확인을 해보니... 

방금 추가한 postNum의 데이터가 없네요 .....ㅜㅜ  콘솔로 일단 터미널을 찍어보니

 

postNum: undefined.. 

postNum은 들어가 있는데....🤣      다시 공식문서로.. 

 

 

 

공식문서를 봐도 이해가 잘 안가서 외국 해결예시를 찾다가 좋은 글 발견!!

 

결론은 

First, the callback from a Mongoose find returns an array ... findOne will return a single object.

find()는 배열을 반환하고 findOne은 단일 객체를 반환한다고 합니다. (객체인데 배열로 반환해서 문제가?)

 

findOne으로 바꿔주니 값이 잘 출력되네요 (findOne은 하나의 doc를 찾을때 사용한다고 해요..)

 

 

find() 적용시 오류 터미널 log 값

 
  [
    {
      _id: new ObjectId("647a06e9dc7d16334b2c79c5"),
      name: 'counter',
      postNum: 4
    }
  ]
  { title: '123', content: '123', postNum: undefined }
 

 

 

findOne() 적용시 터미널 log 값

 
  {
    _id: new ObjectId("647a06e9dc7d16334b2c79c5"),
    name: 'counter',
    postNum: 5
  }
  { title: '123', content: '123', postNum: 5 }
 

 

 

 

 

몽고DB에 가서 보면 초기에 세팅값을 1을 넣어서 

2개 게시글 upload한 상황이라 counter 스키마쪽 데이터는 3으로 카운트 되었구요

 

 

testPosts에서는 upload글마다  고유의 num이 확인 되었습니다 😀

작성 글들을 지우고 다시 작성해도 counter는 계속 증가로 고유의 num을 갖을 수 있습니다!! 

 

 

출처  http://corpus.hubwiz.com/2/node.js/31210243.html

 

Mongoose find() returns undefined property and strange object

I have a bug that i can't resolve because for the first time it happen to me. here is my query : Pack.find( {idclient: clientId } ) .populate({ path: 'cards', options: { sort: { 'position': 1 } } }) . exec(function(err,pack){ if(err){ console.log(err); }el

corpus.hubwiz.com

 

 

728x90
반응형