inflearn logo
강의

Course

Instructor

[Renewed] Node.js Textbook - From Basics to Project Practice

Using Sequelize

시퀄라이즈 연결질문...

Resolved

492

rmatlr0112

3 asked

0

require('dotenv').config();
const PORT = process.env.PORT;
const dotenv = require('dotenv');
const express = require('express');
const compression = require("compression");
const methodOverride = require("method-override");
const cors  = require("cors");
const userRouter = require("./routes/userRoute");
const boardRouter = require("./routes/boardRoute");
const authRouter = require('./routes/auth'); // 인증 라우터
const ejsMate = require('ejs-mate');
const path = require('path');
const session = require('express-session');
const morgan = require('morgan');
const nunjucks = require('nunjucks');
const passport = require('passport');
const passportConfig = require('./passport');
const { sequelize } = require('../models/index');
const cookieParser = require('cookie-parser');
const app = express();

passportConfig();


nunjucks.configure('views', {
    express : app,
    watch : true,
});

sequelize.sync({ force: true })
    .then(() => {
        console.log("데이터 베이스 연결 성공")
    })
    .catch((err) => {
        console.log(err);
    });




app.engine('ejs', ejsMate)
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'))

app.use(express.urlencoded({ extended: true }));
app.use(compression());
app.use(express.json());
app.use(express.urlencoded({extended:true}));
app.use(methodOverride());
app.use(cors());
app.use(cookieParser(process.env.COOKIE_SECRET));
app.use(
   session({
      resave: false,
      saveUninitialized: false,
      secret: process.env.COOKIE_SECRET,
      cookie: {
         httpOnly: true,
         secure: false,
      },
   }),
);
//! express-session에 의존하므로 뒤에 위치해야 함
app.use(passport.initialize()); // 요청 객체에 passport 설정을 심음
app.use(passport.session()); // req.session 객체에 passport정보를 추가 저장
// passport.session()이 실행되면, 세션쿠키 정보를 바탕으로 해서 passport/index.js의 deserializeUser()가 실행하게 한다.
 


app.use('/', userRouter);
app.use('/', boardRouter);
app.use('/auth', authRouter);






app.get('/', (req,res)=>{
    res.render('home')
})






app.listen(PORT, () => {
    console.log(`SERVING ON THE ${PORT}`);
})

module.exports = app;

<env파일>

DB_HOST = localhost

DB_USER = root

DB_PASS = tkfkdgo12

DB_NAME = nodejs

PORT = 3000

JWT_SECRET = softsquared_jwt_secret_key_07040014087

COOKIE_SECRET = cookiesecret

KAKAO_ID = bcb213727449d2b53039dcca5f541c02

const Sequelize = require('sequelize'); const path = require('path'); const env = process.env.NODE_ENV || 'development'; const User = require('./user'); // config/config.json 파일에 있는 설정값들을 불러온다. // config객체의 env변수(development)키 의 객체값들을 불러온다. // 즉, 데이터베이스 설정을 불러온다고 말할 수 있다. const config = require('../config/config')[env] const db = {}; // new Sequelize를 통해 MySQL 연결 객체를 생성한다. const sequelize = new Sequelize(config.database, config.username, config.password, config) // 연결객체를 나중에 재사용하기 위해 db.sequelize에 넣어둔다. db.Sequelize = Sequelize; db.sequelize = sequelize; User.init(sequelize); // 모듈로 꺼낸다. module.exports = db;

 

 

<models 폴더 내 index.js>

const Sequelize = require('sequelize');
const path = require('path');
const env = process.env.NODE_ENV || 'development';
const User = require('./user');

// config/config.json 파일에 있는 설정값들을 불러온다.
// config객체의 env변수(development)키 의 객체값들을 불러온다.
// 즉, 데이터베이스 설정을 불러온다고 말할 수 있다.
const config = require('../config/config')[env]
 
const db = {};
 
// new Sequelize를 통해 MySQL 연결 객체를 생성한다.
const sequelize = new Sequelize(config.database, config.username, config.password, config)
 
// 연결객체를 나중에 재사용하기 위해 db.sequelize에 넣어둔다.
db.Sequelize = Sequelize;
db.sequelize = sequelize;
User.init(sequelize);

// 모듈로 꺼낸다.
module.exports = db;

 

 

<config.json>{ "development": { "username": "root", "password": "tkfkdgo12", "database": "nodejs", "host": "localhost", "dialect": "mysql" }, "test": { "username": "root", "password": null, "database": "database_test", "host": "127.0.0.1", "dialect": "mysql" }, "production": { "username": "root", "password": null, "database": "database_production", "host": "127.0.0.1", "dialect": "mysql" } }

 

<오류메시지>

비밀번호 설정도 다해줬는데 모르겠습니다 ㅠㅠ

스크린샷 2022-11-27 오후 9.42.17.png

 

Sequelize mysql nodejs mongodb

Answer 2

0

mpband4869

강의대로 따라서 코드 작성 후 npm start로 실행하니

 

sequelize.sync({force:false})

^

TypeError: sequelize.sync is not a function

[nodemon] app crashed - waiting for file changes before starting...

라고 뜹니다 ㅜ

0

zerocho

require 부분을 빠뜨리신것 같습니다.

0

mpband4869

require도 문제 없어서 다시 천천히 보니

db.sequelize = sequelize; 를

대문자로 db.sequelize = Sequelize; 로 적어서 오류났네요

답글 달아주셔서 감사합니다

 

0

zerocho

혹시 config.json 말고 config.js도 있나요? process.env.NODE_ENV도 콘솔로그 찍어보세요.

0

rmatlr0112

config.js 는 없는데, 이것과는 별개로 그전에 database Nodejs랑 연결한답시고 config 폴더 내 database.js 파일을 만들어서

아래와 같은 코드 입력하고 데이터베이스를 연결해준 이력이 있는데 이것과 충돌이 일어나는걸까요?

require("dotenv").config();
const mysql = require("mysql2/promise");



const config = 
{
    host: `${process.env.DB_HOST}`,
    user:`${process.env.DB_USER}`,
    port: `3306`,
    password: `${process.env.DB_PASS}`,
    database: `${process.env.DB_NAME}`
}

const pool = mysql.createPool(config);

module.exports = pool;

0

zerocho

가장 확실한 건 model/index.js에서 console.log(config) 해보세요

0

rmatlr0112

const Sequelize = require('sequelize');
const path = require('path');
const env = process.env.NODE_ENV || 'development';
const User = require('./user');

// config/config.json 파일에 있는 설정값들을 불러온다.
// config객체의 env변수(development)키 의 객체값들을 불러온다.
// 즉, 데이터베이스 설정을 불러온다고 말할 수 있다.
const config = require('../config/config')[env]
console.log(config);
const db = {};
 
// new Sequelize를 통해 MySQL 연결 객체를 생성한다.
const sequelize = new Sequelize(config.database, config.username, config.password, config)
 
// 연결객체를 나중에 재사용하기 위해 db.sequelize에 넣어둔다.
db.Sequelize = Sequelize;
db.sequelize = sequelize;
User.init(sequelize);


// 모듈로 꺼낸다.
module.exports = db;

이렇게 console.log(config) 해줫는데 같은 오류만 나옵니다 ㅠㅠ

 

스크린샷 2022-11-28 오전 12.12.24.png

0

rmatlr0112

엇,,,혹시 몰라서 위에서 말씀드린 database.js 에 console.log(config)하니깐 얘에서는 찍히는데 그럼 얘가 먼저 선수?치고있어서 시퀄라이즈가 연결을 못시킨다고 봐야할까요?

0

rmatlr0112

스크린샷 2022-11-28 오전 12.19.36.png

0

zerocho

네 그런 듯 합니다.

0

rmatlr0112

아 그러면,, 시퀄라이즈를 쓰는거면 다음과 같이 데이터베이스 연결시켜주는 코드가 필요없게 되는걸까요? 어차피 시퀄라이즈 자체가 데이터베이스와 연동되니깐요 ?


const pool = mysql.createPool(config);
module.exports = pool;

 

0

zerocho

네 필요없습니다. 시퀄라이즈에서 알아서 연결 맺습니다.

0

rmatlr0112

으앗,,또 하나 배웠네요 감사합니다 제로초님 짱짱맨!!

리눅스 노드 설치시 패키지

0

159

0

socket.js 에서 referer로부터 roomId를 가져올 때

0

904

3

스트리밍 방식으로 대용량 파일 업로드 & 다운로드 관련 질문

0

2281

2

a[title] 질문드립니다

0

375

1

리뉴얼 강의 및 공부 방법

0

581

1

jwt decode

0

1128

1

node.js 교과서 3판 질문드립니다

0

391

1

passport와 jwt

0

432

1

리뉴얼 강의

0

417

2

혹시 Node.js 교과서 3판 이북은 언제 나오나요?

0

353

1

몽고디비 사용자도 MYSQL부분을 들어야 하나요???

0

481

1

sql 쿼리 로그는 어떤 모듈이 작성하나요?

0

505

2

nunjucks res.render('error'); 작동을 안합니다.

0

511

1

질문있습니다.

0

346

1

multer 한글 파일 업로드시 파일명이 깨져요.

1

3535

1

수업자료는 어디있나요?

0

366

1

질문 있습니디

0

235

1

multer 사용시 file 외 name값은 못받나용?

0

416

1

코드 중복 부분 질문드립니다.

0

298

1

api 만드는 이유 질문드립니다.

0

286

1

Strategy의 done에 대해 질문드립니다.

0

361

1

안녕하세요 fs 권한 관련 질문드립니다

0

446

1

res.setHeader vs res.cookie

0

1785

3

실무에서의 에러처리에 대해 질문드립니다.

0

203

1