5
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

node.jsのORM - sequelize get started

Last updated at Posted at 2014-06-24

事前準備

Expressパッケージを用意する

cd /path/to
express -e appName  ※1
cd appName
npm install

注)※1を/path/to/appName でやらないこと

sequelizeモジュールをインストールする

npm install --save sequalize

sequalizeでDB操作する

sequelizeをrequireする

var Sequelize = require('sequelize');

テーブルを定義する

// MySQLに接続
var sequelize = new Sequelize('express', 'root', null, {
  host: "localhost",
  port: 3306
});

// テーブル定義する
var User = sequelize.define('User', {
  name: Sequelize.STRING
});

sequelizeでテーブルを作る

sequelize
  .sync({force: true})
  .complete(function(err) {
    if (!!err) {
      console.log('An error occured while creating the table:', err);
    }else {
      console.log('It worked!');
    }
  });

sequelizeでINSERTする

User
  .create({
    name: 'UserB'
  })
  .complete(function(err, user) {
    if (!!err) {
      console.log('The instance has not been saved: ' + err);
    } else {
      console.log('We have persisted instance now');
    }
  });

sequalizeでSELECTする

User
  .find({ where: { name: 'UserA' } })
  .complete(function(err, UserA) {
    if (!!err) {
      console.log('An error occurred while searching for UserA:', err);
    } else if (!UserA) {
      console.log('No user with the username "UserA" has been found.');
    } else {
      console.log('Hello ' + UserA.name + '!');
      console.log('All attributes of UserA:', UserA.values);
    }
  });
5
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?