Sequelize 개요

brandon·2023년 5월 28일
0

MySQL

목록 보기
2/4

Sequelize 는 production dependency이기에 --save 를 사용한다.

npm i --save sequelize

1. Database 에 연결하기

Database에 연결하기 위해서는 sequelize instance를 만들어야 한다.

util/database.js:

const Sequelize = require('sequelize');

//(database이름, 유저이름, 비밀번호, 옵션)
const sequelize = new Sequelize('node-complete', 'root', 'password', {
    host: 'localhost', 
    dialect: 'mysql'
});

module.exports = sequelize;

2. Model 만들기

database.js에서 export 된 sequelize instance에 define method를 사용한다.

Model 이름은 소문자이다.

const Product = sequelize.define('product', {
  id: {
    type: Sequelize.INTEGER,
    autoIncrement: true, 
    allowNull: false, 
    primaryKey: true
  }, 
  title: {
    type: Sequelize.STRING, 
    allowNull: false
  }, 
  price: {
    type: Sequelize.DOUBLE, 
    allowNull: false
  },
  description: {
    type: Sequelize.STRING, 
    allowNull: false
  }, 
  imageURL: {
    type: Sequelize.STRING, 
    allowNull: false
  }
});

3. Sync()로 테이블 만들기

sequelize.sync()는 테이블을 생성한다.
그전에 mysql서버에 schema가 존재해야 한다. workbench에서 만들자.

//app.js 파일

sequelize.sync().then(result => {
    console.log(result);
    app.listen(3000);
})
.catch(err => {
    console.log(err);
})

결과:
Executing (default): CREATE TABLE IF NOT EXISTS products (id INTEGER NOT NULL auto_increment , title VARCHAR(255) NOT NULL, price DOUBLE PRECISION NOT NULL, description VARCHAR(255) NOT NULL, imageURL VARCHAR(255) NOT NULL, createdAt DATETIME NOT NULL, updatedAt DATETIME NOT NULL, PRIMARY KEY (id)) ENGINE=InnoDB;..

이렇게 테이블 생성 SQL을 자동으로 실행시킨다.
App.listen(3000)이 then()안에 없고 밖에 있다면 sync()는 asynchronous이기 때문에 table이 생성 되기 전에 페이지가 로드 될 수 있다.

4. Database에 추가하기

modelName.create() 나 modelName.build() 로 데이터 항목을 추가할 수 있다.

1. create()

이미 define된 product모델을 사용한다.

//form data
const title = req.body.title;
const imageUrl = req.body.imageUrl;
const price = req.body.price;
const description = req.body.description;


Product.create({
    title: title,
    price: price,
    description: description,
    imageURL: imageUrl
  }).then(result => {
    console.log('created product');
  }).catch(err => {
    console.log(err);
  })

2. SomeModel.createModel()

만약 SomeModel이 Model의 parent model일때, createModel()을 통하여 Model table에 데이터를 생성하고 SomeModel의 id값을 저장할 수 있다.

//User.hasMany(Product);
//Prouct.belongsTo(User);

  const title = req.body.title;
  const imageUrl = req.body.imageUrl;
  const price = req.body.price;
  const description = req.body.description;
  req.user.createProduct({
    title: title,
    price: price,
    imageURL: imageUrl,
    description: description
  }).then(product => {
    res.redirect('/admin/products');
  });

3. build()

create()는 한번에 database에 추가하는 반면 build는 save()를 사용하여 따로 저장 해주어야 한다.

const product = Product.build({
  title: title,
    price: price,
    description: description,
    imageURL: imageUrl
});

product.save()
  .then(result => {
    console.log(result);
  })
  .catch(err => {
    console.log(err);
  })

5. 찾기

공식 문서:
https://sequelize.org/docs/v6/core-concepts/model-querying-finders/

여러가지 방법들이 있다.

1. Model.findByPk(primaryKey)

말 그대로 primary key로 찾는 방법이다.
하나의 model instance 만 반환한다.

Product.findByPk(prodId)
  .then(product => {
    res.render('shop/product-detail', {
      product: product,
      pageTitle: product.title,
      path: '/products'
    });
  });

2. Model.findAll({ where: {id: id}})

where 를 사용해 조건에 맞는 instance들이 들어있는 array를 반환한다.

Product.findAll({ where: { id : prodId }})
  .then(products => {
    res.render('shop/product-detail', {
      product: products[0],
      pageTitle: products[0].title,
      path: '/products'
    });
  })

위와 차이는 products 배열이라는 것이다.

6. update

업데이트 할때는 save()를 하면 된다.

const prodId = req.body.productId;
  const updatedTitle = req.body.title;
  const updatedPrice = req.body.price;
  const updatedImageUrl = req.body.imageUrl;
  const updatedDesc = req.body.description;
  Product.findByPk(prodId)
    .then(product => {
      product.title = updatedTitle; 
      product.price = updatedPrice;
      product.imageURL = updatedImageUrl; 
      product.description = updatedDesc; 
      
      return product.save();
      
    })
    .then(result => {
      console.log('product edited!');
      res.redirect('/admin/products');
    })
    .catch(err => {
      console.log(err);
    });

7. destroy()

삭제 할때는 destroy()를 사용하면 된다.
여기서도 Model.destroy({ where: {id: id} }) 같이 조건을 사용하거나
findByPk().then(result => result.destroy())처럼 instance를 찾아 destroy할 수 있다.

const prodId = req.body.productId;
Product.destroy({ where: {id: prodId }});

//or 

const prodId = req.body.productId;
Product.findByPk(prodId)
  .then(product => {
    product.destroy();
  });
profile
everything happens for a reason

0개의 댓글