안녕세계

[Node.js] Sequelize 본문

[Node.js] Sequelize

Junhong Kim 2016. 9. 27. 00:43
728x90
반응형

* 자바스크립트 환경설정

(웹스톰 전체) Default Preferences > Languages & Frameworkds > JavaScript > JavaScript language version [ECMAScript 6]

(웹스톰 특정) Preferences > Languages & Frameworkds > JavaScript > JavaScript language version [ECMAScript 6] 



- Sequelize로 만드는 Restful API -


[step1] Model Define




[step2] CRUD


(1) Create


(2) Read


(3) Update


(4) Delete


config/sequelize : 데이터베이스 연결


util/ : 기능 모음

util/db.js : 데이터베이스에 대한 기능

util/commons.js : 공통 기능


models: 모델 모음


controller/... : routes에 대한 기능들


routes : routes를 묶어둔 것




// 테이블 정의

var Customer = sequelize.define('customer', {
name: {
type: Sequelize.STRING
},
email: {
type: Sequelize.STRING
}
});


// 레코드 추가

Customer.create({
name: 'park',
email: 'gun0912@selphone.co.kr'
});


// 레코드 조회

Customer.findAll({
where: {id: 1}
}).then(function(users) {
res.send({
message: users
});
})

// 레코드 업데이트


module.exports.adoptComment = function(data) {
return models.Comment.update({
adopt: true
}, {
where: { id: data.cid }
});
};



// include 옵션을 통해 전체(*) select를 구현할 수 있음

Eater.findAll({
attributes: {include: []}
}).then(function(results) {
for(var index in results) {
console.log(results[index].dataValues);
}
});

[sequeliz 에서 제공하는 예제] 

// This is a tiresome way of getting the number of hats... Model.findAll({ attributes: ['id', 'foo', 'bar', 'baz', 'quz', [sequelize.fn('COUNT', sequelize.col('hats')), 'no_hats']] }); // This is shorter, and less error prone because it still works if you add / remove attributes Model.findAll({ attributes: { include: [[sequelize.fn('COUNT', sequelize.col('hats')), 'no_hats']] } });




// default 설정 셋팅

var Eater = db.define('eater', {
user_id: {
type: Sequelize.STRING,
primaryKey: true,
references: {
model: User,
key: 'id'
}
}
}, {
timestamps: false,
tableName: 'eater'
});

* Sequelize는 default 로 'id' / 'updatedAt' / 'createdAt' 속성 값이 만들어진다.

- 1) 'id' 값이 필요하지 않을 경우 다른 기본키로 지정할 속성에 primaryKey: true 옵션을 지정해준다.

Eater.removeAttribute('id');

   2) Mode.removeAttribute('id');

- 'updatedAt'과 'createdAt' 속성이 필요하지 않을 경우 모델의 옵션(?) 값으로 timestamps: false 옵션을 지정해준다.

- table 네임은 db.define('eater' ...  ) 지정할 경우 복수로 테이블이 생성된다. 그러므로 내가 원하는 테이블 명으로 지정하기 위해서는 tableName: 'eater' 처럼 직접 지정




// 관계와 조인, 관계를 설정해야 조인을 할 수 있다.

Eater.belongsTo(User, {foreignKey: 'user_id'});


// 조인을 하기 위해서는 include 옵션을 사용한다.

Eater.findAll({
include:[
{
model:User,
where:{
gender:'Female'
}
}
]
}).then(function(results) {
for(var index in results) {
console.log(results[index].dataValues);
}
});

// 한 단계 더 발전하여 Scope라는 기능을 사용할 수 있다.

scope를 사용할 때 defaultScope는 필수 임

var Eater = db.define('eater', {
user_id: {
type: Sequelize.STRING,
primaryKey: true
// references: {
// model: User,
// key: 'id'
// }
}
}, {
timestamps: false,
tableName: 'eater',
defaultScope:{
include:[
{
model:User,
where:{
gender:'Female'
}
}
]
},
scopes:{
none:{
}
}
});


// N:M 관계는 대상 테이블을 관계를 갖는 테이블 두개를 1:N 관계로 풀어서 해결하자


[Target Keys]

Target Key는 Target  model의 column이다.


The target key is the column on the target model that the foreign key column on the source model points to. By default the target key for a belongsTo relation will be the target model's primary key. To define a custom column, use the targetKeyoption.



[Include]

module.exports.findAllByConditionWithJoin = function(model, withModel, condition) {
return model.findAll({
include: [{
model: withModel,
}],
where: condition
});
};
module.exports.findAllByConditionWithJoin = function(model, withModel, condition) {
return model.findAll({
include: [{
model: withModel, where: condition
}],

});
};


// ---

워크벤치로 스키마와 테이블을 생성한뒤에

Sequelize로 재생성 해준다.


findById는 특정 아이디로 해당 아이디의 모든 속성을 보여준다. (프라이머리 키가 기준이 되는 것임 그래서 하나 밖에 안나옴)

findOne은 하나의 아이디를 가져온다


//

req.body 로 요청 바디를 다 가져올 수 있음


update는 인스턴스를 업데이트 할 수 있음 --> 매우 편리



//

.then(function() { // 성공시 처리

)

.catch(function() { // 에러시 처리

)


https://blog.weirdx.io/post/2544


// TODO: update 할 때 fields 속성이 뭔지? (fields는 바꿀꺼를 지정해주는 거임)
// TODO: return 해서 다음 then 으로 넘기는게 맞는지? (맞긴한데 프로미스 형식으로 쓰셈)


//

http://docs.sequelizejs.com/en/latest/api/sequelize/?highlight=timezone

시퀄라이저ㅇㅔ서  default 설정을 ㅅ바꾸ㅡㅓ줄 수있다;


Class Sequelize 는 다양한 옵션을 설정할 수 있다.

var Sequelize = require('sequelize');

timezone도 timezone: '09:00' 처럼 해주면 된다.


// moment.js 라이브러리를 사용하여

DATE와 관련된 것을 쉽게 활용할 수 있따

moment().format('YYYY') - moment(user.birth).format('YYYY') + 1


// increment

increment(fields, [options]) -> Promise.<this>

View code

Increment the value of one or more columns. This is done in the database, which means it does not use the values currently stored on the Instance. The increment is done using a

SET column = column + X

query. To get the correct value after an increment into the Instance you should do a reload.

instance.increment('number') // increment number by 1
instance.increment(['number', 'count'], { by: 2 }) // increment number and count by 2
instance.increment({ answer: 42, tries: 1}, { by: 2 }) // increment answer by 42, and tries by 1.
                                                       // `by` is ignored, since each column has its own value
if (req.url.match(/\?kind=\w+&pageNo=\d+&rowCount=\d+/i))

이거를


if(req.query.keyword){

바꿔서 쓰면 됨

그러면 keyword가 있으면 undefined가 아니기 떄문에 해당 블럭이 수행됨

뒤에 pageNo rowCount는 알아서 req.query 받아서 넘겨주기 때문에 일일히 저ㄹㅓㅎ게 안적어 줘도됨


// req.body로 모든 body의 내용을 가져올 수 있음

// findById , find 류를 사용해서 instance를 만들어주자

// promise.prop --> 병행수행


// 161014

- bluebird

- lodash / undescorejs 

- Promise pattern

- increment / decrement

- sequelize에서 transcation 처리



* 앞으로 반영해야할 과제

routes & controller & models & util


models : sequelize db 모델

routes : url 경로만 만들어 두고

controller : 해당 routes의 기능을 수행하게 만듬

util : model의 기능을 수행

common: 동일한 기능 묶어서 관리



* MAC nodemon

설치 : sudo npm install -g nodemn

사용 : sudo nodemon bin/www




항상 기본적으로 조인이 필요할 떄 defaultScope사용 --> 조인문을 미리마ㄴㅡㄹ어 놓고 유연하게ㅐ 사용이가ㄴㅡㅇ

var Post = sequelize.define('post', {
title: {
type: Sequelize.STRING
},
contents: {
type: Sequelize.STRING
},
like: {
type: Sequelize.INTEGER
},
category: {
type: Sequelize.STRING
}
}, {
defaultScope: {
include: User
},
tableName: 'post'
});








※ Sequelize 참조 사이트

http://sequelize.readthedocs.io/en/latest/

https://hyunseob.github.io/2016/03/27/usage-of-sequelize-js/

http://blog.jeonghwan.net/sequalize-%EC%BF%BC%EB%A6%AC/

728x90
반응형
Comments