2019-03-10
공식문서 Sequelize를 사용하면, JS 코드 내에 SQL 쿼리문을 작성할 필요가 없다. 테이블 생성, 레코드 추가 등의 쿼리를 method와 오브젝트로 대신할 수 있다. 익히고 나면 훨씬 편하게 DB와 상호작용할 수 있다고 한다.
/* You'll need to
* npm install sequelize
* before running this example. Documentation is at http://sequelizejs.com/
*/
var Sequelize = require('sequelize');
var db = new Sequelize('chatter', 'root', '');
/* TODO this constructor takes the database name, username, then password.
* Modify the arguments if you need to */
/* first define the data structure by giving property names and datatypes
* See http://sequelizejs.com for other datatypes you can use besides STRING. */
var User = db.define('User', {
username: Sequelize.STRING
});
var Message = db.define('Message', {
userid: Sequelize.INTEGER,
text: Sequelize.STRING,
roomname: Sequelize.STRING
});
/* Sequelize comes with built in support for promises
* making it easy to chain asynchronous operations together */
User.sync()
.then(function() {
// Now instantiate an object and save it:
return User.create({username: 'Jean Valjean'});
})
.then(function() {
// Retrieve objects from the database:
return User.findAll({ where: {username: 'Jean Valjean'} });
})
.then(function(users) {
users.forEach(function(user) {
console.log(user.username + ' exists');
});
db.close();
})
.catch(function(err) {
// Handle any error in the chain
console.error(err);
db.close();
});