[mongoose]북마크 하기/안하기 (count가 음수까지 가는것에대하여..)

김예진·2022년 1월 16일
0

북마크 하기/안하기를 하고 있다. 여러 블로그 글도 참고하고, 몽구스, 몽고디비 문서까지 찾아보면서 기능을 구현중인데

1. 북마크하기

userDAO.js(디비에 쿼리문을 날리는 파일)

// 북마크 하기
const createUserBookmark = async (userId, postId) => {
  
  const result = await Post.findOneAndUpdate(
    { postId: postId },
    {
      $push: { userBookmark: { _id: userId._id } },
      $inc: { 'count.bookmark': 1 },
    },
    { new: true }
  );
  
  const newBookmark = await new Bookmark({
    postId: result._id,
    userId: userId._id,
  }).save(); //.save()가 있어야 저장됨. 꼭 넣어주기

  return result;
};
  • 1) Post 문서에 userBookmark 배열안에 user의 객체아이디를 추가, 북마크 카운트를 +1한다.
    2) Bookmark문서에 post의 객체 아이디와 user의 객체 아이디를 가진 새로운 객체 생성

2. 북마크 취소하기

// 북마크 취소하기 
const removeUserBookmark = async (userId, postId) => {
  
  const result = await Post.findOneAndUpdate(
    { postId: postId },
    {
      $pull: { userBookmark: { _id: userId._id } },
      $inc: { 'count.bookmark': -1 },
    },
    { new: true }
  );
  
  const deleteBookmark = await Bookmark.findOneAndDelete({
    $and: [{ postId: result._id }, { userId: userId._id }],
  });
 
  return result;
  • 1) Post에서 postId를 가진 문서(이때 postId는 type이 number인 유니크한 아이디다)를 찾아서 userBookmark 배열에서 user 객체 아이디를 삭제, 카운트 -1 한다.
    2) Bookmark문서에서 post 객체 아이디와 user객체 아이디를 가진 객체를 찾아서 삭제

북마크 취소의 결과가..

{
    "status": "success",
    "result": {
        "count": {
            "bookmark": -5, //북마크....카운트가..
            "comment": 0
        },
        "_id": "61e198e51d1e8221f37a0a4c",
        "postId": 10,
        "writer": "61e119213f93bb1013a7510a",
        "category": "novel",
        "content": "ㅍㅏㅇㅣㅌㅣㅇ",
        "createdAt": "2022-01-15 00:37:55",
        "userBookmark": [
            "61e27c68497feff6162ae4f7"
        ],
        "__v": 0
    }
}

문제는 userBookmark 배열 안에 유저 아이디가 없으면 삭제는 안되는데, 카운트가 계속 -가 된다는것^^... 계-속! ^^..물론 프론트에서 조건문을 걸어서 Post/Delete요청을 해주겠지만 그래도 서버에서 한번 더 조건을 걸어줘야할 것 같았다.

findOneUpdate를 POST요청시 있으면 생성x , DELETE 요청시 더 이상 없으면 삭제x 이런식으로도 고민했지만..

exists()를 사용해보자

exists()는 있는지 없는지 boolean값으로 결과를 반환한다. 이걸 사용해서 바꿔볼건데

참고할 자료들 :
https://simplernerd.com/mongoose-id-exists/

https://www.geeksforgeeks.org/mongoose-exists-function/

따라서 이것이 주어진 필터와 일치하는 문서가 데이터베이스에 하나 이상 있으면 true를 반환하고 그렇지 않으면 false를 반환하는 mongoose exist() 함수를 사용하는 방법입니다.

일단 해야할 것이..

1. Bookmark schema 수정하기

현재 Bookmark schema는 이렇다

import mongoose from 'mongoose';

const Schema = mongoose.Schema;

const bookmarkSchema = new Schema({
  postId: {
    type: mongoose.Types.ObjectId,
    ref: 'Post',
    required: true,
    index: true,
  },
  userId: {
    type: mongoose.Types.ObjectId,
    ref: 'User',
    required: true,
    index: true,
  },
});

const Bookmark = mongoose.model('Bookmark', bookmarkSchema);

export default Bookmark;

postId와 userId는 몽구스의 객체 아이디를 참조하고 있는데 .. 객체 아이디는 post_id, user_id로 바꾸고 postId는 Post 문서에서 내가 임의로 만든 number 타입의 아이디를 하나 더 갖도록 수정해야할 것 같다.

profile
Backend Developer 🌱 벨로그 내용을 티스토리로 이사중~!

0개의 댓글