[Node] findAll 메소드 활용하여 Database 조회하기
BE/NodeJS 2023. 5. 15.
Sequelize를 사용하였고, ClientInfo 라는 모델을 예시로 작성 할 예정이다.
이미 데이터베이스와 모델을 연결하였다는 가정 하에 진행한다.
더보기: 모델이란?
더보기
모델(Model)은 데이터베이스(Database)에 있는 테이블(Table)의 데이터를 CRUD하는 역할을 한다.
본문에서는 CLIENT 라는 데이터베이스에 ClientInfo 라는 모델을 연결하여 사용한다.
findAll() 메소드는 Promise 객체를 리턴한다. // 데이터 전체 조회
만약 .then() 이나, async...await...을 사용하지 않으면 코드를 다 작성하고 GET HTTP 메소드로 요청하였을 때 빈 객체가 온다.
더보기: 코드리뷰
더보기
findAll() 에서 데이터를 조회하고, 조회한 데이터를 Promise에 담아서 다음 인자로 전달한다.
then() 에서는 인자를 받고 콘솔에 출력한다.
catch() 는 에러처리 역할을 한다.
ClientInfo.findAll() // ClientInfo 모델로 findAll 메소드를 사용해서 데이터를 조회한다.
.then(info => {
console.log(info);
})
.catch(error => {
console.error(error);
});
findAll({ where: { 조건 } }) // 데이터 조건 조회
다음은 .then() 대신 async, await을 사용하였다. 조건 부분에 key:value 형태로 넣으면, 조건에 부합한 데이터만 골라서 리턴한다.
조건 부분에 where: { name } 이렇게 작성된 이유는 key와 value의 값이 같을 경우 이렇게 작성이 가능하다.
app.get('/info', async (req, res) => { // async
const { name } = req.query;
if ( name ) {
const Client = await ClientInfo.findAll({ where: { name } }); // await
res.send(Client)
} else {
const Clients = await ClientInfo.findAll(); // await
res.send(Clients);
};
'BE > NodeJS' 카테고리의 다른 글
[Node.js] 유효성 검사(Validation), express-validator 사용법 (0) | 2023.05.28 |
---|---|
[Node] findOne 메소드와 조건추가 이해하기 (0) | 2023.05.15 |
[Node] mySQL과 Sequelize를 이용한 데이터베이스 설정 (0) | 2023.05.14 |
[Express] 라우팅 메소드 put과 delete 이해와 예시 (0) | 2023.05.13 |
[Node.js] readFile과 createReadStream 비교 및 활용방법 (0) | 2023.05.13 |