0616 Sequelize
2021. 6. 16. 12:42ㆍNode.js
시퀼라이즈=ORM은 자바스크립트 객체와 데이터베이스의 릴레이션을 매핑해주는 도구이다.
npm init -y
npm i sequelize mysql2
npm i express
npm i supervisor
npm i sequelize-cli -g
sequelize init
const express = require ('express');
const app = express();
const {Sequelize} = require('sequelize');
const sequelize = new Sequelize('mysql','root','qwerpoiu!@#',{
host:'localhost',
dialect: 'mysql'
});
app.get('/',(req,res)=>{
res.send('hello world');
})
app.get('/connetdb',(req,res)=>{
connect();
res.send('db connected');
});
async function connect(){
try{
await sequelize.authenticate(); //접속 대기
console.log('connected');
}
catch(err){
console.log(err);
}
}
app.listen(3000,()=>{
console.log('server is running at port 3000');
});
https://sequelize.org/master/manual/getting-started.html
suquelize init 을 하면 config 파일이 생성된다.
//config.json
{
"development": {
"username": "root",
"password": "qwerpoiu!@",
"database": "sequelize_db",
"host": "127.0.0.1",
"dialect": "mysql",
"timezone": "+09:00"
},
"test": {
"username": "root",
"password": "qwerpoiu!@",
"database": "database_test",
"host": "127.0.0.1",
"dialect": "mysql"
},
"production": {
"username": "root",
"password": "qwerpoiu!@",
"database": "database_production",
"host": "127.0.0.1",
"dialect": "mysql"
},
"define":{
"charset":"utf8",
"collate":"utf8_bin",
"timestamps":"true"
}
}
npm i sequelize-auto
시퀄라이즈를 더 사용하기 편하게 매핑해둔 npm - 데이터 테이블을 오브젝트로 만들어준다.
//auto.js
const express = require ('express');
const app = express();
const SequelizeAuto = require('sequelize-auto');
const auto = new SequelizeAuto('nodejs','root','qwerpoiu!@#',{
host:'localhost',
port:'3306',
dialect:'mysql'
});
auto.run(err=>{
if(err) throw err;
console.log('complete');
});
findAll( ) 함수 사용하기
https://velog.io/@cadenzah/sequelize-document-2
//mySequelize.js
const initModel = require('./models/init-models');
const {Op,Sequelize} = require('sequelize');
const sequelize = new Sequelize('nodejs','root','qwerpoiu!@#',{
host:'localhost',
dialect:'mysql'
});
const models = initModel(sequelize);
module.exports={
models,
Op,
};
모듈로 export 했다.
//findall.js
const {Op,models} = require('./mySequelize');
// models.users.findAll().then(results=>{
// console.log(results);
// });
async function findAllFromProducts(){
const product = await models.products.findAll({
where: {
price:{
[Op.gt]: 45000
},
},
});
const json =JSON.stringify(product);
console.log(json);
};
findAllFromProducts();
const {Op,models} = require('./mySequelize');
// models.users.findAll().then(results=>{
// console.log(results);
// });
async function findAllFromProducts(){
const product = await models.products.findAll({
where: {
price:{
[Op.gt]: 45000
},
name:{
[Op.eq]:'닌텐도 스위치 본체 모여봐요 동물의숲 에디션'
},
},
});
const json =JSON.stringify(product);
console.log(json);
};
findAllFromProducts();
sequelize를 이용해 express 서버에 db불러오기
//mySequelize.js
const initModel = require('./models/init-models');
const {Op,Sequelize} = require('sequelize');
const sequelize = new Sequelize('nodejs','root','qwerpoiu!@#',{
host:'localhost',
dialect:'mysql'
});
const models = initModel(sequelize);
module.exports={
models,
Op,
};
//app.js
const {Op,models} = require('./mySequelize');
const express = require('express');
const app = express();
app.get('/',(req,res)=>{
res.send('hello world');
});
app.listen(3000,()=>{
console.log('server is running at 3000');
});
app.get('/users/all',async (req,res)=>{
const json = await findAllFromUsers();
console.log(res.body);
res.send(json);
})
app.get('/users/:id',async (req,res)=>{
const json = await findAllFromID();
console.log(res.body);
res.send(json);
})
async function findAllFromUsers(){
const users = await models.users.findAll();
const json =JSON.stringify(users);
console.log(json);
};
async function findAllFromID(){
const users = await models.users.findAll({
where:{
id:{
[Op.eq]: '4'
},
},
});
const json =JSON.stringify(users);
console.log(json);
};
'Node.js' 카테고리의 다른 글
GPGS Achievement (0) | 2021.06.23 |
---|---|
0617 GPGS (0) | 2021.06.17 |
0615 express서버와 mysql 커넥션 (0) | 2021.06.15 |
0611 express 서버 이어서 (0) | 2021.06.11 |
0610 서버 데이터 전송 방법에 따라 구현하기 (0) | 2021.06.10 |