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

mongoDB 게시글에 시간 나타내기

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

 

 

server단 post 스키마에서 timestamps: true 설정하면 등록시간, 업데이트시간을 사용 가능합니다.

 
  timestamps: true
 
 
  const postSchema = new mongoose.Schema(
  {
    title: String,
    content: String,
    postNum: Number,
    image: String,
    author: {
      type: mongoose.Schema.Types.ObjectId,
      ref: "User",
    },
     //댓글 갯수를 알기 위해서 repleNum 추가
      repleNum: {
      type: Number,
      default: 0,
      },
    },
    { collection: "posts", timestamps: true }
  );
  const Post = mongoose.model("Post", postSchema);
 

 

 

 

mongoDB에서 확인을 해보면 설정이 추가 된 것을 확인할 수 있습니다.

 

 

 

위에 출력된 시간 형식으로 사용하면 가독성이 떨어지므로

moment라는 라이브러리를 사용해서 다듬어서 아래의 공식페이지 예시처럼 사용하겠습니다.

moment().format('MMMM Do YYYY, h:mm:ss a'); // 6월 8일 2023, 1:26:55 오전
moment().format('dddd');                    // 목요일
moment().format("MMM Do YY");               // 6월 8일 23
moment().format('YYYY [escaped] YYYY');     // 2023 escaped 2023
moment().format();                         

 

출처 https://momentjs.com/

 

Moment.js | Home

Format Dates moment().format('MMMM Do YYYY, h:mm:ss a'); moment().format('dddd'); moment().format("MMM Do YY"); moment().format('YYYY [escaped] YYYY'); moment().format(); Relative Time moment("20111031", "YYYYMMDD").fromNow(); moment("20120620", "YYYYMMDD"

momentjs.com

 

 

 

 

client 코드

SetTime 함수에 인자로 (생성시간,업데이트시간)을 받아서 

a와b의 시간이 같지 않다면 if문으로 updatedAt시간을 받아서 출력해주고

같다면(else) createdAt시간으로 등록시간을 출력

 
  const SetTime = (a, b) => {
      if (a !== b) {
        return moment(b).format("YYYY년 MMMM Do h:mm a") + " (수정완료)";
      } else {
        return moment(a).format("YYYY년 MMMM Do h:mm a");
      }
    };
 
 
         <p className="time">
           {SetTime(post.createdAt, post.updatedAt)}
         </p>
 

 

 

 

 

게시글이 수정되었다면 아래와 같이 업데이트된 시간과 수정완료 글자가 보여집니다.

 

728x90
반응형