最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to fix Sequelize update issue? - Stack Overflow

programmeradmin1浏览0评论

I use MySQL ORM. But update method not working.

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

Sequelize Log:

Executing (default): UPDATE Users SET ResetPasswordToken=?,updatedAt=? WHERE UserName = ?

I use MySQL ORM. But update method not working.

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

Sequelize Log:

Executing (default): UPDATE Users SET ResetPasswordToken=?,updatedAt=? WHERE UserName = ?

Share Improve this question asked Jan 11, 2021 at 16:44 Göktuğ OzleyenGöktuğ Ozleyen 1212 silver badges16 bronze badges 0
Add a ment  | 

2 Answers 2

Reset to default 7

According to the official documentation of Sequelize, save method is used for updating an instance. Please check this page for more detail.

This has been mentioned in the documentation:

If you change the value of some field of an instance, calling save again will update it accordingly:


    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!

Similarly, your code can be written as:


    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']});
    }

You can update several fields at once with the set method:

const jane = await User.create({ name: "Jane" });

jane.set({
  name: "Ada",
  favoriteColor: "blue"
});
// As above, the database still has "Jane" and "green"
await jane.save();
// The database now has "Ada" and "blue" for name and favorite color
发布评论

评论列表(0)

  1. 暂无评论