首页 文章

如何使用节点的sequelize更新记录?

提问于
浏览
73

我正在使用NodeJS,express,express-resource和Sequelize创建一个RESTful 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更新记录的正确方法是什么?

7 回答

  • 72

    我没有使用Sequelize,但在阅读了它的文档后,显然你是instantiating a new object,这就是Sequelize在数据库中插入新记录的原因 .

    首先,你需要搜索该记录,获取它,并且只有在更改了它的属性后才能获取它,例如:update

    Project.find({ where: { title: 'aProject' } })
      .on('success', function (project) {
        // Check if record exists in db
        if (project) {
          project.updateAttributes({
            title: 'a very different title now'
          })
          .success(function () {})
        }
      })
    
  • 5

    从版本2.0.0开始,您需要将 where 子句包装在 where 属性中:

    Project.update(
      { title: 'a very different title now' },
      { where: { _id: 1 } }
    )
      .success(result =>
        handleResult(result)
      )
      .error(err =>
        handleError(err)
      )
    

    更新2016-03-09

    最新版本实际上不再使用 successerror ,而是使用 then -able promises .

    所以上面的代码如下:

    Project.update(
      { title: 'a very different title now' },
      { where: { _id: 1 } }
    )
      .then(result =>
        handleResult(result)
      )
      .catch(err =>
        handleError(err)
      )
    

    http://docs.sequelizejs.com/en/latest/api/model/#updatevalues-options-promisearrayaffectedcount-affectedrows

  • 146

    从sequelize v1.7.0开始,您现在可以在模型上调用update()方法 . 更清洁

    例如:

    Project.update(
    
      // Set Attribute values 
            { title:'a very different title now' },
    
      // Where clause / criteria 
             { _id : 1 }     
    
     ).success(function() { 
    
         console.log("Project with id =1 updated successfully!");
    
     }).error(function(err) { 
    
         console.log("Project update failed !");
         //handle error here
    
     });
    
  • 1

    我认为使用 UPDATE ... WHERE 正如herehere所解释的那样是一种精益方法

    Project.update(
          { title: 'a very different title no' } /* set attributes' value */, 
          { where: { _id : 1 }} /* where criteria */
    ).then(function(affectedRows) {
    Project.findAll().then(function(Projects) {
         console.log(Projects) 
    })
    
  • 8

    不推荐使用此解决方案

    fail | fail | error()已弃用,将在2.1中删除,请改用promise-style .

    所以你必须使用

    Project.update(
    
        // Set Attribute values 
        {
            title: 'a very different title now'
        },
    
        // Where clause / criteria 
        {
            _id: 1
        }
    
    ).then(function() {
    
        console.log("Project with id =1 updated successfully!");
    
    }).catch(function(e) {
        console.log("Project update failed !");
    })
    

    你也可以使用.complete()

    问候

  • 28

    public static update(values:Object,options:Object):Promise>

    检查文档http://docs.sequelizejs.com/class/lib/model.js~Model.html#static-method-update

    Project.update(
        // Set Attribute values 
        { title:'a very different title now' },
      // Where clause / criteria 
         { _id : 1 }     
      ).then(function(result) { 
    
     //it returns an array as [affectedCount, affectedRows]
    
      })
    
  • 1

    对于在2018年12月寻找答案的人来说,这是使用promises的正确语法:

    Project.update(
        // Values to update
        {
            title:  'a very different title now'
        },
        { // Clause
            where: 
            {
                id: 1
            }
        }
    ).then(count => {
        console.log('Rows updated ' + count);
    });
    

相关问题