【问题标题】:How to update a record using sequelize for node?如何使用节点的续集更新记录?
【发布时间】:2011-12-30 18:57:32
【问题描述】:

我正在使用 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 更新记录的正确方法是什么?

【问题讨论】:

    标签: mysql node.js express sequelize.js


    【解决方案1】:
    var whereStatement = {};
    
      whereStatement.id = req.userId;
    
      if (whereStatement) {
        User.findOne({
          where: whereStatement
        })
          .then(user => {
    
            if (user) {
              
              var updateuserdetails = {
                email: req.body.email,
                mobile: req.body.mobile,
                status: req.body.status,
                user_type_id: req.body.user_type_id
              };
    
              user.update(
                updateuserdetails
              )
                .then(function () {
                  res.status(200).send({ message: 'Success...' });
                })
                .catch(err => {
                  res.status(500).send({ message: err.message });
                });
            }
    
            
          })
    

    【讨论】:

      【解决方案2】:

      有两种方法可以更新 sequelize 中的记录。

      首先,如果你有一个唯一的标识符,那么你可以使用 where 子句,或者如果你想用相同的标识符更新多条记录。

      您可以创建要更新的整个对象或特定列

      const objectToUpdate = {
      title: 'Hello World',
      description: 'Hello World'
      }
      
      models.Locale.update(objectToUpdate, { where: { id: 2}})
      
      

      仅更新特定列

      models.Locale.update({ title: 'Hello World'}, { where: { id: 2}})
      

      其次,您可以使用查找查询来找到它并使用设置和保存功能来更新数据库。

      
      const objectToUpdate = {
      title: 'Hello World',
      description: 'Hello World'
      }
      
      models.Locale.findAll({ where: { title: 'Hello World'}}).then((result) => {
         if(result){
         // Result is array because we have used findAll. We can use findOne as well if you want one row and update that.
              result[0].set(objectToUpdate);
              result[0].save(); // This is a promise
      }
      })
      

      在更新或创建新行时始终使用事务。这样,如果出现任何错误或您进行任何多次更新,它将回滚任何更新:

      
      models.sequelize.transaction((tx) => {
          models.Locale.update(objectToUpdate, { transaction: tx, where: {id: 2}});
      })
      

      【讨论】:

        【解决方案3】:

        我使用 update 方法来更新我的记录。

        1. models 是一个 .js 文件,用于放置模型
        2. users 是型号名称
        3. 更新是由 sequelize 提供的内置函数。
        4. 我正在将名称和城市更新到用户表中,其中 id 等于 1
        models.users.update(
            {
             "name":'sam',
        "city":'USA'
            },
            where:{
            id:1
            }
            )
        

        【讨论】:

        • 您可以添加对您的代码的解释吗?那会很有帮助
        • 现在可以理解了吗?
        • 是的,非常!谢谢
        • 我认为它会抛出一个错误,因为属性“where”在括号之外
        【解决方案4】:

        如果Model.update 语句不适合你,你可以这样尝试:

        try{ 
            await sequelize.query('update posts set param=:param where conditionparam=:conditionparam', {replacements: {param: 'parameter', conditionparam:'condition'}, type: QueryTypes.UPDATE})
        }
        catch(err){
            console.log(err)
        }
        

        【讨论】:

          【解决方案5】:

          我是这样做的:

          Model.findOne({
              where: {
                condtions
              }
            }).then( j => {
              return j.update({
                field you want to update
              }).then( r => {
                return res.status(200).json({msg: 'succesfully updated'});
              }).catch(e => {
                return res.status(400).json({msg: 'error ' +e});
              })
            }).catch( e => {
              return res.status(400).json({msg: 'error ' +e});
            });
          

          【讨论】:

            【解决方案6】:

            我在下面的代码中使用了sequelize.jsnode.jstransaction,并添加了适当的错误处理,如果它找不到数据,它会抛出错误,即找不到具有该 id 的数据

            editLocale: async (req, res) => {
            
                sequelize.sequelize.transaction(async (t1) => {
            
                    if (!req.body.id) {
                        logger.warn(error.MANDATORY_FIELDS);
                        return res.status(500).send(error.MANDATORY_FIELDS);
                    }
            
                    let id = req.body.id;
            
                    let checkLocale= await sequelize.Locale.findOne({
                        where: {
                            id : req.body.id
                        }
                    });
            
                    checkLocale = checkLocale.get();
                    if (checkLocale ) {
                        let Locale= await sequelize.Locale.update(req.body, {
                            where: {
                                id: id
                            }
                        });
            
                        let result = error.OK;
                        result.data = Locale;
            
                        logger.info(result);
                        return res.status(200).send(result);
                    }
                    else {
                        logger.warn(error.DATA_NOT_FOUND);
                        return res.status(404).send(error.DATA_NOT_FOUND);
                    }
                }).catch(function (err) {
                    logger.error(err);
                    return res.status(500).send(error.SERVER_ERROR);
                });
            },
            

            【讨论】:

              【解决方案7】:

              2020 年 1 月答案
              要理解的是,模型有一个更新方法,而实例(记录)有一个单独的更新方法。 Model.update() 更新所有匹配的记录并返回一个数组see Sequelize documentationInstance.update() 更新记录并返回一个实例对象。

              所以要更新每个问题的单个记录,代码如下所示:

              SequlizeModel.findOne({where: {id: 'some-id'}})
              .then(record => {
                
                if (!record) {
                  throw new Error('No record found')
                }
              
                console.log(`retrieved record ${JSON.stringify(record,null,2)}`) 
              
                let values = {
                  registered : true,
                  email: 'some@email.com',
                  name: 'Joe Blogs'
                }
                
                record.update(values).then( updatedRecord => {
                  console.log(`updated record ${JSON.stringify(updatedRecord,null,2)}`)
                  // login into your DB and confirm update
                })
              
              })
              .catch((error) => {
                // do seomthing with the error
                throw new Error(error)
              })
              

              因此,使用Model.findOne()Model.findByPkId() 获取单个实例(记录)的句柄,然后使用Instance.update()

              【讨论】:

              • model.update(data, { where: {id: 1} });根据@kube 的回答,仍在 202 v6.x 中工作
              • 问题是,这需要两个 SQL 事务(选择和更新)而不是一个(更新)。
              【解决方案8】:

              如果您在这里寻找增加模型中特定字段值的方法...

              截至sequelize@5.21.3,这对我有用

              User.increment("field", {by: 1, where: {id: 1});

              参考号:https://github.com/sequelize/sequelize/issues/7268

              【讨论】:

                【解决方案9】:

                你好,更新记录很简单

                1. sequelize 按 ID(或按您想要的)查找记录
                2. 然后你用result.feild = updatedField 传递参数
                3. 如果数据库中不存在该记录,则使用参数创建一条新记录
                4. 观看示例以获得更多理解 代码 #1 测试 V4 下所有版本的代码
                const sequelizeModel = require("../models/sequelizeModel");
                    const id = req.params.id;
                            sequelizeModel.findAll(id)
                            .then((result)=>{
                                result.name = updatedName;
                                result.lastname = updatedLastname;
                                result.price = updatedPrice;
                                result.tele = updatedTele;
                                return result.save()
                            })
                            .then((result)=>{
                                    console.log("the data was Updated");
                                })
                            .catch((err)=>{
                                console.log("Error : ",err)
                            });
                

                V5 代码

                const id = req.params.id;
                            const name = req.body.name;
                            const lastname = req.body.lastname;
                            const tele = req.body.tele;
                            const price = req.body.price;
                    StudentWork.update(
                        {
                            name        : name,
                            lastname    : lastname,
                            tele        : tele,
                            price       : price
                        },
                        {returning: true, where: {id: id} }
                      )
                            .then((result)=>{
                                console.log("data was Updated");
                                res.redirect('/');
                            })
                    .catch((err)=>{
                        console.log("Error : ",err)
                    });
                

                【讨论】:

                  【解决方案10】:

                  从 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 年 3 月 9 日更新

                  最新版本实际上不再使用successerror,而是使用then-able 承诺。

                  所以上面的代码如下所示:

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

                  使用异步/等待

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

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

                  【讨论】:

                  【解决方案11】:

                  你可以使用 Model.update() 方法。

                  使用异步/等待:

                  try{
                    const result = await Project.update(
                      { title: "Updated Title" }, //what going to be updated
                      { where: { id: 1 }} // where clause
                    )  
                  } catch (error) {
                    // error handling
                  }
                  

                  使用 .then().catch():

                  Project.update(
                      { title: "Updated Title" }, //what going to be updated
                      { where: { id: 1 }} // where clause
                  )
                  .then(result => {
                    // code with result
                  })
                  .catch(error => {
                    // error handling
                  })
                  

                  【讨论】:

                    【解决方案12】:

                    在现代 javascript Es6 中使用 async 和 await

                    const title = "title goes here";
                    const id = 1;
                    
                        try{
                        const result = await Project.update(
                              { title },
                              { where: { id } }
                            )
                        }.catch(err => console.log(err));
                    

                    你可以返回结果...

                    【讨论】:

                      【解决方案13】:

                      我没有用过Sequelize,但是看了它的文档,很明显你是instantiating a new object,这就是为什么Sequelize会在db中插入一条新记录。

                      首先您需要搜索该记录,获取它,然后才更改其属性和update 它,例如:

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

                      【讨论】:

                      • 这行得通,但是我必须将 .success 更改为 .then
                      • 应该是Project.findOne(
                      • 老问题,但与今天搜索相关(就像我一样)。从 Sequelize 5 开始,查找记录的正确方法是使用 findByPk(req.params.id) 返回一个实例。
                      • 不建议这样做,它发送 2 个查询,可以通过单个查询完成。请检查下面的其他答案。
                      【解决方案14】:

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

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

                      【讨论】:

                      • 这应该是最佳答案。
                      • 在 2019 年不起作用:未处理的拒绝错误:无效值 [函数]
                      • 在 Sequelize 6.6.2(2021 年 6 月)上运行良好。
                      【解决方案15】:

                      公共静态更新(值:对象,选项:对象): 承诺>

                      检查文档一次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]
                      
                        })
                      

                      【讨论】:

                        【解决方案16】:

                        此解决方案已弃用

                        failure|fail|error() 已弃用,将在 2.1 中删除,请 请改用 promise 样式。

                        所以你必须使用

                        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()

                        问候

                        【讨论】:

                          【解决方案17】:

                          我认为使用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) 
                          })
                          

                          【讨论】:

                          • 这应该是公认的答案。这样你只能设置一些字段,你可以指定条件。非常感谢:)
                          【解决方案18】:

                          从 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
                          
                           });
                          

                          【讨论】:

                          猜你喜欢
                          • 2020-04-16
                          • 1970-01-01
                          • 1970-01-01
                          • 1970-01-01
                          • 1970-01-01
                          • 1970-01-01
                          • 2020-08-18
                          • 2019-08-26
                          • 1970-01-01
                          相关资源
                          最近更新 更多