๐ฌ ๐Node.js ๊ต๊ณผ์๐๋ฅผ ์ธ๊ฐ์ผ๋ก ๊ณต๋ถ ์ค์ธ๋ฐ ํ๋ก์ ํธ ๋ฐ๋ผํ๋ฉด์ ๊ทธ๋ฅ ๋ฌด์์ ๋ฐ๋ผํ๊ธฐ ๋ณด๋ค๋
์ ๋ชจ๋ฅด๊ฒ ๋๊ฑฐ ํ๋ฒ ์ง๊ณ ๋์ด๊ฐ๋ ค ํ๋ค.
sequelize์ ๋ํด์ ๋ค๋ค์คฌ์๋๋ฐ ๋๋ฌด ์งง๊ฒ ๋ค๋ค์ ํ๋ก์ ํธ ํ๋ฉด์ ์ด๊ฒ ๋ฌด์จ ๋ฉ์๋ ์ง ์ด๋ป๊ฒ ๋์ํ๋์ง ์ ๋๋ ์์์ผ๊ฒ ์ด์ ๋ฐ๋ก ์ ๋ฆฌ...โ๏ธ
sequelize๋ก ๋ฐ์ดํฐ๋ฅผ DB์ ์ถ๊ฐํ ๋๋ create()๋ฉ์๋๋ฅผ ์ฌ์ฉํ๋ค!
...
const { Post } = require('../models');
...
router.post('/',async (req,res,next)=>{
let body = req.body;
Post.create({
title : body.postTitle,
author : body.author
})
.then(result => {
console.log("success");
})
.catch(err => {
console.log("fail");
})
});
๐ฏ ์ฐธ๊ณ ๋ก sequelize๋ Promise ๋ฌธ๋ฒ์ด ๋ด๋ถ์ ์ผ๋ก ๋์ํ๊ธฐ ๋๋ฌธ์ ์ฟผ๋ฆฌ๊ฐ ์ ์ํ๋์์ผ๋ฉด then() ๋ฉ์๋๊ฐ ์ํ๋๋ค.
router.get('/hashtag',async(req,res,next)=>{
const query = req.query.hashtag;
if(!query){
return res.redirect('/');
}
try{
const hashtag = await Hashtag.findOne({where:{title:query}});
let posts = [];
if(hashtag){
// A.getB : ๊ด๊ณ์๋ row ์กฐํ
// A.addB : ๊ด๊ณ ์์ฑ
// A.setB : ๊ด๊ณ ์์
// A.removeB : ๊ด๊ณ ์ ๊ฑฐ
post = await hashtag.getPosts({
include : [{model : User}]
})
}
return res.render('main',{
title : `${query} | Nodebird`,
user : req.user,
tiwits : posts, // ๊ฒ์ ๊ฒฐ๊ณผ
})
}catch(error){
console.error(error)
next(error);
}
})
...
const { Post } = require('../models');
...
router.post('/:id',async (req,res,next)=>{
let body = req.body;
let postId = req.params.id
Post.update({
title : body.postTitle,
author : body.author
},{
where : {id:postId}
})
.then(result => {
console.log("success");
})
.catch(err => {
console.log("fail");
})
});
...
const { Post } = require('../models');
...
router.delete('/:id',async (req,res,next)=>{
let postId = req.params.id
Post.destroy({
where : {id:postId}
})
.then(result => {
console.log("success");
})
.catch(err => {
console.log("fail");
})
});
์ด๋ ๊ฒ ์ ๋ฆฌํ๋๊น ์ด์ ์ข sequelize์ ๋ํ ๊ฐ์ด ์ค๋๋ฏ!
๋ฌด์์ ๋ฐ๋ผ์น์ง ๋ง์!