Sequelize란 Node.js 에서 sql을 사용할 수 있게 해주는 라이브러리이다. Sequelize는 ORM 으로 분류된다. ORM 이란 Object-Relation Mapping 의 약자로 객체와 데이터베이스 간의 맵핑을 해주는 도구이다.
Sequelize를 사용하면 JavaScript 에서 mysql 을 사용할 수 있는 것도 ORM 이기 때문이다.
Sequelize 쿼리는 promis를 반환하므로 then 이나 async/await 문법도 사용이 가능하다.
레코드 생성하기
User.create({
name : 'kimcoding',
age : 31,
jop : wep developer
});
레코드 조회 하기
findOne - 한가지만 조회
module.export = async (req,res) =>{
let result = await User.fineOne({where: {id:id}})
res.send(result)
}
findAll - 모든 데이터 조회
User.findAll()
// findOne은 한가지만 찾는것이고 findAll은 전부 다 조회 하는것이다.
특정 칼럼 조회
- attributes 옵션 사용
User.findAll({
attributes: ['name','age']
});
조건부 조회하기
- where, Op 객체 이용
User.findAll({
attributes:['name','age'],
where: {name : 'kimcoding',
age:{[Op.lte]:20}
}
})
* Op 객체
- Op.gt - 초과
- Op.gte - 이상
- Op.lt - 미만
- Op.lte - 이하
- Op.ne - 같지않음
- Op.or - 또는
- Op.in - 배열 요소 중 하나
- Op.notIn - 배열 요소 와 모두 다름
정렬하기
- order
User.findAll({
attribues:['name','age'],
order:['age','DESC']
});
조회할 레코드 갯수 제한
-limite, offset
User.findAll({
attributes: ['name', 'age'],
order: [['age', 'DESC']],
limit: 1,
});
레코드 수정하기
- update
User.uadate({
comment:'수정하기'
},{
where:{age:31}
});
레코드 삭제하기
- destroy
User.destroy({
where:{id:3}
});
관계쿼리
- include
user 와 comment 가 1:N 관계를 맺고 있다고 가정해보자. 그럴때 include를 사용하면 된다.
const user = await User.findOne({
include: [{
model: Comment
}]
});
'TIL' 카테고리의 다른 글
| [node.js] multer 미들웨어를 이용해 서버에서 파일 다루기 (0) | 2022.02.24 |
|---|---|
| [React] react-router-dom v6 에 대해 (0) | 2022.01.14 |
| Git branch (0) | 2021.12.01 |
| MVC 패턴 (0) | 2021.11.22 |
| 2021. 10 .27 Styled-Component (0) | 2021.10.27 |