*이 글을 읽기전에 작성자 개인의견이 있으니, 다른 블로그와 교차로 읽는것을 권장합니다.*
sequelize와 MongoDB활용을 위해 새로운 branch를 생성하고 전환합니다.
branch 생성과 동시에 전환하기
git checkout -b 브랜치이름
1. Sequelize
Sequalize 사이트: https://sequelize.org/
Sequelize
Sequelize is a modern TypeScript and Node.js ORM for Oracle, Postgres, MySQL, MariaDB, SQLite and SQL Server, and more. Featuring solid transaction support, relations, eager and lazy loading, read replication and more.
sequelize.org
node.js에서 mysql 등 RDBMS를 쉽게 다룰 수 있도록 도와주는 라이브러리입니다. sequelize라이브러리를 이용하기 위해서 설치합니다.
// sequelize 설치하기
npm i sequelize
controller > auth.js 파일, data > auth.js파일, tweet.js파일, db > database.js 파일, app.js파일을 수정합니다.
// controller > auth.js 파일
import * as authRepository from '../data/auth.js';
import bcrypt from 'bcrypt';
import jwt from 'jsonwebtoken';
import { config } from '../config.js';
function createJwtToken(id){
return jwt.sign({id}, config.jwt.secretKey, {expiresIn: config.jwt.expiresInSec});
}
export async function signup(req, res, next){
let {username, password, name, email, url} = req.body;
const found = await authRepository.findByUsername(username);
if(found){
return res.status(409).json({message:`${username}이 이미 있습니다`});
}
password = await bcrypt.hash(password, config.bcrypt.saltRounds);
const userId = await authRepository.createUser({username, password, name, email, url});
const token = createJwtToken(userId);
res.status(201).json({token, username});
}
export async function login(req, res, next){
const {username, password} = req.body;
// const user = await authRepository.login(username);
const user = await authRepository.findByUsername(username);
console.log(user);
if(!user){
return res.status(401).json({message: `아이디를 찾을 수 없음`});
}
const isValidpassword = await bcrypt.compareSync(password, user.password);
if(!isValidpassword){
return res.status(401).json({message: `비밀번호가 틀렸음`});
}
const token = createJwtToken(user.id);
res.status(200).json({token, username});
}
// export async function verify(req, res, next){
// const token = req.header['Token'];
// if(token){
// res.status(200).json(token);
// }
// }
export async function me(req, res, next){
const user = await authRepository.findById(req.userId);
console.log(user);
if(!user){
return res.status(404).json({message: `일치하는 사용자가 없음`});
}
res.status(200).json({token: req.token, username: user.username});
}
// data > auth.js 파일
import SQ from 'sequelize';
import { sequelize } from '../db/database.js';
const DataTypes = SQ.DataTypes;
export const User = sequelize.define(
'user',
{
id: {
type: DataTypes.INTEGER,
autoIncrement: true,
allowNull: false,
primaryKey: true
},
username: {
type: DataTypes.STRING(50),
allowNull: false
},
password: {
type: DataTypes.STRING(150),
allowNull: false
},
name: {
type: DataTypes.STRING(50),
allowNull: false
},
email: {
type: DataTypes.STRING(50),
allowNull: false
},
url: DataTypes.STRING(1000)
},
{ timestamps: false }
);
// 아이디(username) 중복검사
export async function findByUsername(username){
return User.findOne({where: {username}});
}
// id 중복검사
export async function findById(id){
return User.findByPk(id);
}
export async function createUser(user){
return User.create(user).then((data) => data.dataValues.id)
}
// data > tweet.js 파일
import SQ from 'sequelize';
import { sequelize } from '../db/database.js';
import { User } from './auth.js';
const DataTypes = SQ.DataTypes;
const Sequelize = sequelize;
const INCLUDE_USER = {
attributes: [
'id',
'text',
'createdAt',
'userId',
[Sequelize.col('user.name'), 'name'],
[Sequelize.col('user.username'), 'username'],
[Sequelize.col('user.url'), 'url']
],
include: {
model: User,
attributes: [],
}
}
const ORDER_DESC = {
order: [['createdAt', 'DESC']]
}
const Tweet = sequelize.define('tweet', {
id: {
type: DataTypes.INTEGER,
autoIncrement: true,
allowNull: false,
primaryKey: true
},
text: {
type: DataTypes.TEXT,
allowNull: false
}
}, { timestamps: false });
Tweet.belongsTo(User);
// 모든 트윗을 리턴
export async function getAll() {
return Tweet.findAll({ ...INCLUDE_USER, ...ORDER_DESC });
}
// 해당 아이디에 대한 트윗을 리턴
export async function getAllByUsername(username){
return Tweet.findAll({ ...INCLUDE_USER, ...ORDER_DESC, include: {
...INCLUDE_USER.include, where: {username}
} });
}
// 글번호에 대한 트윗을 리턴
export async function getById(id){
return Tweet.findOne({ where: {id}, ...INCLUDE_USER });
}
// 트윗을 작성
export async function create(text, userId){
return Tweet.create({ text, userId }).then((data) => this.getById(data.dataValues.id));
}
// 트윗을 변경
export async function update(id, text){
return Tweet.findByPk(id, INCLUDE_USER).then((tweet) => {
tweet.text = text;
return tweet.save();
});
}
// 트윗을 삭제
export async function remove(id){
return Tweet.findByPk(id).then((tweet) => {
tweet.destroy();
});
}
// db > database.js 파일
import { config } from '../config.js';
import SQ from 'sequelize';
const {host, user, database, password, port} = config.db;
export const sequelize = new SQ.Sequelize(database, user, password, {
host,
dialect: 'mysql',
logging: false
})
// app.js 파일
import express from "express";
import morgan from "morgan";
import tweetsRouter from './router/tweets.js';
import authRouter from './router/auth.js';
import { config } from "./config.js";
import {sequelize} from "./db/database.js";
const app = express();
app.use(express.json());
app.use(morgan("dev"));
app.use('/tweets', tweetsRouter);
app.use('/auth', authRouter);
app.use((req, res, next) => {
res.sendStatus(404);
});
// DB 연결 테스트!
sequelize.sync().then(() => {
app.listen(config.host.port);
});
2. MongoDB
- MongoDB는 NoSQL 데이터베이스로 문서 기반 데이터 저장 방식을 채택한 오픈소스 DBMS입니다.
- 관계형 데이터베이스(RDBMS)와는 달리 schema가 없으며, BSON(Binary JSON) 형태로 데이터를 저장합니다.
- 유연성이 좋고, 대규모 데이터 처리에 용이합니다.
MongoDB Atlas
- MongoDB의 관리형 클라우드 데이터베이스 서비스입니다.
- MongoDB 데이터베이스를 클라우드에서 호스팅하고 관리하는 것을 중심으로 하며, 개발자 및 기업이 손쉽게 애플리케이션을 빌드하고 배포할 수 있도록 지원합니다.
MongoDB사이트 : https://www.mongodb.com/ko-kr
MongoDB: 개발자 데이터 플랫폼
업계 최고의 최신 데이터베이스를 토대로 구축된 개발자 데이터 플랫폼을 사용해 아이디어를 더욱 빠르게 실현하세요. 공통 쿼리 인터페이스와 개발자들이 원하는 데이터 모델을 사용하는 동
www.mongodb.com
MongoDB Node만들기-홈페이지 참조
https://www.mongodb.com/docs/drivers/node/current/
MongoDB Node Driver - Node.js Driver v6.5
Docs Home → Develop Applications → MongoDB Drivers → Node.js Driver Welcome to the documentation site for the official MongoDB Node.js driver. You can add the driver to your application to work with MongoDB in JavaScript or TypeScript. For more infor
www.mongodb.com
MongoDB 확인하기
postman으로 오류발생시, router > tweet.js파일, controller > tweet.js 파일, data > tweet.js 파일에서 함수이름, argument이름 확인하시면 됩니다.
'JavaScript > Node JS' 카테고리의 다른 글
Java Script(18)-Mongoose (0) | 2024.05.10 |
---|---|
Java Script(16)-MySQL DBMS node.js연동 (0) | 2024.05.08 |
Java Script(12)-Refactoring(리팩토링), validate(데이터 검증) (0) | 2024.04.29 |
Java Script(11)-미들웨어 요청방식 실습: tweets (0) | 2024.04.26 |
Java Script(10)-route메서드, morgan (0) | 2024.04.25 |