【问题标题】:How to fix Sequelize update issue?如何解决 Sequelize 更新问题?
【发布时间】:2021-01-11 16:44:50
【问题描述】:

我使用 MySQL ORM。但是更新方法不起作用。

User.update({
  ResetPasswordToken : resetPasswordToken
},{
  where: {
      UserName: 'testuser'
  }
})

续集日志:

正在执行(默认):UPDATE Users SET ResetPasswordToken=?,updatedAt=?在哪里UserName = ?

【问题讨论】:

    标签: javascript mysql node.js express sequelize.js


    【解决方案1】:

    根据 Sequelize 的官方文档,save 方法用于更新实例。详情请查看this页面。

    这在文档中已经提到:

    如果你改变了实例的某些字段的值,再次调用 save 会相应地更新它:

    
        const jane = await User.create({ name: "Jane" });
        console.log(jane.name); // "Jane"
        jane.name = "Ada";
        // the name is still "Jane" in the database
        await jane.save();
        // Now the name was updated to "Ada" in the database!
    

    同样,你的代码可以写成:

    
        const foo = async (resetPasswordToken) => {
           //Finding current instance of the user
           const currentUser = await User.findOne({
              where:{
                UserName: 'testuser'
              }
           });
           //modifying the related field
           currentUser.ResetPasswordToken = resetPasswordToken;
           //saving the changes
           currentUser.save({fields: ['ResetPasswordToken']});
        }
    
    

    【讨论】:

    • 我不想创建新用户。我想更改旧数据。例如:修改密码
    • 是的,我根据你的问题修改了答案。首先,您可以找到当前用户实例,然后保存相关字段。试一试,我相信它应该可以工作。
    猜你喜欢
    • 2019-09-11
    • 2020-08-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多