CRUD 연습해보기 - slug

Goody·2021년 3월 16일
0

블로그만들기

목록 보기
7/10
post-thumbnail

이번 포스팅에서는 게시글의 제목을 주소로 받는 slug 모듈을 활용해보자.


1. 라이브러리 설치

npm i marked slugify

💡 라이브러리 설명
marked : 마크다운을 입력받아 html로 변환해주는 라이브러리 (이후 포스팅에서 사용 예정)
slugify : 텍스트를 url 주소로 변환해주는 라이브러리


2. 라이브러리 삽입

// models/article.js
const marked = require('marked');
const slugify = require('slugify');

3. slugify 데이터 모델에 적용 적용

// models/article.js
const articleSchema = new mongoose.Schema({
    title: {
        required: true,
        type : String
    },
    description : {
        type : String
    },
    markdown : {
        required: true,
        type : String
    },
    createdAt : {
        type: Date,
        default : Date.now
    },
    slug: {				// slug 컬럼을 새로 추가한다.
        type: String,
        required: true,
        unique: true
    }
})

articleSchema.pre('validate', function(next) {
    if(this.title) {
        this.slug = slugify(this.title, {lower:true, strict:true})
    }
    
    next();
})

데이터스키마는 데이터 모델을 저장, 삭제, 편집할 때마다 해당 데이터를 평가(validate)하는데, pre() 는 모델을 평가(validate)하기 직전에 콜백함수를 실행한다.
즉, 위에서는 데이터가 평가되기 직전에 title 슬러깅해서 this.slug 에 저장하는 거라고 보면 된다.


4. 게시글 본문 라우팅 및 index.ejs 수정

// routes/article.js

router.get('/:slug', async (req, res) => {
    const article = await Article.findOne(req.params.id);
    if (article == null) res.redirect('/');
    res.render(`articles/show`, {article : article});
});
<!-- index.ejs --->
<body>
    <div class = "container">
        <h1 class = "mb-4">Glog Articles</h1>
        <a href = "/articles/new" class = "btn btn-success">New Article </a> 
   
        <% articles.forEach(article => { %>
            <div class = "card mt-4">
                <div class = "card body">
                    <h4 class="card-title"><%= article.title %></h4>
                    <div class = "card-subtitle text-muted mb-2"><%= article.createdAt.toLocaleDateString() %></div>
                    <div class = "card text mb-2"><%= article.description %></div>
                    <a href = "articles/<%= article.slug %>" class = "btn btn-primary">Read More</a>
                </div>
            </div>
        <% }) %>
    </div>
</body>

routes/aritcle.js 의 get() 안에 들어가던 /:id/:slug로 ,
Article.findById() 를 Article.findOne()로 바꿨다. index.ejs 의<%= article.id %><%= article.slug %>` 로 바꿨다.


게시글의 제목이 게시글의 주소가 되었다.


5. deprecation 수정

여기까지 진행하면, 콘솔에 DeprecationWarning 이 뜨는 것을 볼 수 있다.
이는 더이상 사용되지 않는 명령어를 사용한 경우로, 추후 문제가 생길 수 있으므로 수정해주는 것이 좋다.

// server.js

mongoose.connect('mongodb://localhost/blog', {
    useNewUrlParser: true, 
    useUnifiedTopology: true,
    useCreateIndex: true	// deprecationWarning이 추천해준 프로퍼티를 추가했다.
})

deprecation 경고의 발생은 사용중인 MongoDB 의 버전에 따라 다를 수 있다.


이후 포스팅에선 삭제 기능을 구현해보자.

0개의 댓글