LoginSignup
12
10

More than 5 years have passed since last update.

Node.js + Sequelize で複数レコードの更新

Last updated at Posted at 2014-07-20

備忘録です.
Node.js の ORM である Sequelize を使って検索した複数レコードに対して更新をかける処理を書きます.
Document( http://sequelizejs.com/docs/1.7.8/installation )では詳しく触れてなかったような。。。

環境

  • MacOSX (10.9)
  • Node.js (v0.10.29)
  • npm (1.4.14)
  • Squelize (1.7.9)
  • mysql (2.4.1)
  • Underscore.js (1.6.0)

対象レコード

サンプルなので適当です.
id: 1, title: 'sample', description: 'aiueo',
id: 2, title: 'sample', description: 'waaai'
とか適当に用意してみた.

サンプルコード

sample.js

// Sequelize の準備
var Sequelize = require('sequelize');
var sequelize = new Sequelize('sample', 'user', 'password', {
  host: 'localhost',
  port: 3306
});

// Underscore.js 使いたいひと
var _us = require('underscore');

// テーブル定義,作成
var Sample = sequelize(define('Sample', {
  title: Sequelize.STRING,
  description: Sequelize.TEXT
});
Sample.sync();

// 検索,更新
Sample.findAll({where: {title: 'sample'} })
  .success(function(sample) {
    sample.forEach(function(element) {
      element.updateAttributes({
        description: 'pure'
      }).success(function() {
        console.log('success.');
      });
    });

    // Undersocre.js 使いたいひと
    _us.each(sample, function(element, index, array) {
      element.updateAttributes({
        description: 'underscore'
      }).success(function() {
        console.log('success.(underscore)');
      });
    });
  });
});

変わったかな?

ひとこと

今日は目が痛い日でつらたん.コンタクトしたまま寝てはいけない…

12
10
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
12
10