MySQL 如何使用节点的续集更新记录?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8158244/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 21:44:05  来源:igfitidea点击:

How to update a record using sequelize for node?

mysqlnode.jsexpresssequelize.js

提问by a_arias

I'm creating a RESTful API with NodeJS, express, express-resource, and Sequelize that is used to manage datasets stored in a MySQL database.

我正在使用 NodeJS、express、express-resource 和 Sequelize 创建一个 RESTful API,用于管理存储在 MySQL 数据库中的数据集。

I'm trying to figure out how to properly update a record using Sequelize.

我试图弄清楚如何使用 Sequelize 正确更新记录。

I create a model:

我创建了一个模型:

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

Then, in my resource controller, I define an update action.

然后,在我的资源控制器中,我定义了一个更新操作。

In here I want to be able to update the record where the id matches a req.paramsvariable.

在这里,我希望能够更新 id 与req.params变量匹配的记录。

First I build a model and then I use the updateAttributesmethod to update the record.

首先我建立一个模型,然后我使用该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')
}

Now, this does not actually produce an update query as I would expect.

现在,这实际上并没有像我期望的那样产生更新查询。

Instead, an insert query is executed:

相反,执行插入查询:

INSERT INTO `Locales`(`id`, `locale`, `createdAt`, `updatedAt`, `visible`)
VALUES ('1', 'us', '2011-11-16 05:26:09', '2011-11-16 05:26:15', 1)

So my question is: What is the proper way to update a record using Sequelize ORM?

所以我的问题是:使用 Sequelize ORM 更新记录的正确方法是什么?

回答by kube

Since version 2.0.0 you need to wrap your whereclause in a whereproperty:

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

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


Update 2016-03-09

更新 2016-03-09

The latest version actually doesn't use successand erroranymore but instead uses then-able promises.

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

So the upper code will look as follows:

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

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

Using async/await

使用异步/等待

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

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

回答by alessioalex

I have not used Sequelize, but after reading its documentation, it's obvious that you are instantiating a new object, that's why Sequelize inserts a new record into the db.

我没有使用Sequelize,但在阅读其文档后,很明显您正在实例化一个新对象,这就是 Sequelize 将新记录插入数据库的原因。

First you need to search for that record, fetch it and only after that change its properties and updateit, for example:

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

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

回答by Farm

Since sequelize v1.7.0 you can now call an update() method on the model. Much cleaner

从 sequelize v1.7.0 开始,您现在可以在模型上调用 update() 方法。干净多了

For Example:

例如:

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

 });

回答by DonkeyKong

And for people looking for an answer in December 2018, this is the correct syntax using promises:

对于在 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);
});

回答by Hasan A Yousef

I think using UPDATE ... WHEREas explained hereand hereis a lean approach

我认为UPDATE ... WHERE按照这里的解释使用,这里是一种精益方法

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

回答by LaughingBubba

January 2020 Answer
The thing to understand is that there's an update method for the Model and a separate update method for an Instance (record). Model.update()updates ALL matching records and returns an array see Sequelize guide. Instance.update()updates the record and returns an instance object.

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

So to update a single record per the question, the code would look something like this:

因此,要根据问题更新单个记录,代码将如下所示:

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: '[email protected]',
    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)
})

So, use Model.findOne()or Model.findByPkId()to get a handle a single Instance (record) and then use the Instance.update()

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

回答by hussam

This solution is deprecated

此解决方案已弃用

failure|fail|error() is deprecated and will be removed in 2.1, please use promise-style instead.

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

so you have to use

所以你必须使用

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 !");
})

And you can use .complete()as well

你也可以使用.complete(),以及

Regards

问候

回答by Frank HN

Using async and await in a modern javascript Es6

在现代 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));

you can return result ...

你可以返回结果...

回答by Leandro Lima

You can use Model.update() method.

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

With async/await:

使用异步/等待:

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

With .then().catch():

使用 .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
})

回答by bahri noredine

hi to update the record it very simple

嗨,更新记录很简单

  1. sequelize find the record by ID (or by what you want)
  2. then you pass the params with result.feild = updatedField
  3. if the record doesn'texist in database sequelize create a new record with the params
  4. watch the exemple for more understand Code #1 test that code for all version under V4
  1. sequelize 通过 ID(或您想要的)查找记录
  2. 然后你传递参数 result.feild = updatedField
  3. 如果该记录在数据库 sequelize 中不存在,则使用 params 创建一个新记录
  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)
            });

Code for 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)
    });
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)
    });