😁 관계형 데이터베이스의 한계
- 데이터 스키마가 고정적이다.
- 서버를 여러대의 컴퓨터에 분산시키기가 힘들어 확장성이 적다.
🤪 MongoDB 준비(MacOS)
brew update
brew install mongodb/brew/mongodb-community
brew services start mongodb-community
🧐 스키마와 모델
- 스키마는 컬렉션에 들어가는 문서 내부의 각 필드가 어떤 형식으로 되어 있는지 정의 하는 객체이다.
- 모델은 스키마를 사용하여 만든 인스턴스로, 함수들을 지니고 있는 객체이다.
😘 실습 코드
import mongoose from 'mongoose';
const { Schema } = mongoose;
const PostSchema = new Schema({
title: String,
body: String,
tags: [String],
publishedDate: {
type: Date,
default: Date.now,
},
});
const Post = mongoose.model('Post', PostSchema);
export default Post;
import path from 'path';
require('dotenv').config({ path: path.join(__dirname, '../../.env') });
import Koa from 'koa';
import Router from 'koa-router';
import bodyParser from 'koa-bodyparser';
import mongoose from 'mongoose';
import api from './api';
const { PORT, MONGO_URI } = process.env;
mongoose
.connect(MONGO_URI, {
useNewUrlParser: true,
useFindAndModify: false,
useUnifiedTopology: true,
})
.then(() => {
console.log('connected to MongoDB');
})
.catch((e) => {
console.error(e);
});
const app = new Koa();
const router = new Router();
router.use('/api', api.routes());
app.use(bodyParser());
app.use(router.routes()).use(router.allowedMethods());
const port = PORT || 4000;
app.listen(port, () => {
console.log(`Listening to port ${port}`);
});
require = require('esm')(module);
module.exports = require('./main.js');
import Router from 'koa-router';
import * as postsCtrl from './posts.ctrl';
const posts = new Router();
posts.get('/', postsCtrl.list);
posts.post('/', postsCtrl.write);
posts.get('/:id', postsCtrl.read);
posts.delete('/:id', postsCtrl.remove);
posts.put('/:id', postsCtrl.replace);
posts.patch('/:id', postsCtrl.update);
export default posts;
let postId = 1;
const posts = [
{
id: 1,
title: 'title',
body: 'contents',
},
];
export const write = (ctx) => {
const { title, body } = ctx.request.body;
postId += 1;
const post = { id: postId, title, body };
posts.push(post);
ctx.body = post;
};
export const list = (ctx) => {
ctx.body = posts;
};
export const read = (ctx) => {
const { id } = ctx.params;
const post = posts.find((p) => p.id.toString() === id);
if (!post) {
ctx.status = 404;
ctx.body = {
message: 'post doesnt exist',
};
return;
}
ctx.body = post;
};
export const remove = (ctx) => {
const { id } = ctx.params;
const index = posts.findIndex((p) => p.id.toString() === id);
if (index === 1) {
ctx.status = 404;
ctx.body = {
message: 'post doesnt exist',
};
return;
}
posts.splice(index, 1);
ctx.status = 204;
};
export const replace = (ctx) => {
const { id } = ctx.params;
const index = posts.findIndex((p) => p.id.toString() === id);
if (index === -1) {
ctx.status = 404;
ctx.body = {
message: 'post doesnt exist',
};
return;
}
posts[index] = {
id,
...ctx.request.body,
};
ctx.body = posts[index];
};
export const update = (ctx) => {
const { id } = ctx.params;
const index = posts.findIndex((p) => p.id.toString() === id);
if (index === 1) {
ctx.status = 404;
ctx.body = {
message: 'post doesnt exist',
};
return;
}
posts[index] = {
...posts[index],
...ctx.request.body,
};
ctx.body = posts[index];
};
import Router from 'koa-router';
import posts from './posts';
const api = new Router();
api.use('/posts', posts.routes());
export default api;