我正在使用NodeJS,express,express-resource和Sequelize创建一个RESTful API,该API用于管理存储在MySQL数据库中的数据集。
我试图弄清楚如何使用Sequelize正确更新记录。
我创建一个模型:
module.exports = function (sequelize, DataTypes) {
  return sequelize.define('Locale', {
    id: {
      type: DataTypes.INTEGER,
      autoIncrement: true,
      primaryKey: true
    },
    locale: {
      type: DataTypes.STRING,
      allowNull: false,
      unique: true,
      validate: {
        len: 2
      }
    },
    visible: {
      type: DataTypes.BOOLEAN,
      defaultValue: 1
    }
  })
}
然后,在资源控制器中,定义一个更新操作。
在这里,我希望能够更新ID与req.params变量匹配的记录。
首先,我建立一个模型,然后使用该updateAttributes方法来更新记录。
const Sequelize = require('sequelize')
const { dbconfig } = require('../config.js')
// Initialize database connection
const sequelize = new Sequelize(dbconfig.database, dbconfig.username, dbconfig.password)
// Locale model
const Locales = sequelize.import(__dirname + './models/Locale')
// Create schema if necessary
Locales.sync()
/**
 * PUT /locale/:id
 */
exports.update = function (req, res) {
  if (req.body.name) {
    const loc = Locales.build()
    loc.updateAttributes({
      locale: req.body.name
    })
      .on('success', id => {
        res.json({
          success: true
        }, 200)
      })
      .on('failure', error => {
        throw new Error(error)
      })
  }
  else
    throw new Error('Data not provided')
}
现在,这实际上并没有产生我期望的更新查询。
而是执行插入查询:
INSERT INTO `Locales`(`id`, `locale`, `createdAt`, `updatedAt`, `visible`)
VALUES ('1', 'us', '2011-11-16 05:26:09', '2011-11-16 05:26:15', 1)
所以我的问题是:使用Sequelize ORM更新记录的正确方法是什么?
.success为.then