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

时间:2022-03-17 17:11:04

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.params variable.

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

First I build a model and then I use the updateAttributes method 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更新记录的正确方式是什么?

6 个解决方案

#1


65  

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将一个新记录插入到db中。

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

首先,您需要搜索该记录,获取它,只有在此之后更改它的属性并更新它,例如:

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

#2


122  

Since version 2.0.0 you need to wrap your where clause in a where property:

由于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

The latest version actually doesn't use success and error anymore but instead uses then-able promises.

最新版本实际上不再使用成功和错误,而是使用当时可以实现的承诺。

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

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

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

#3


27  

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

 });

#4


8  

I think using UPDATE ... WHERE as explained here and here is a lean approach

我认为使用更新……这里解释了什么,这里有一个精益方法吗

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

#5


4  

This solution is deprecated

不建议使用这个解决方案

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

失败|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

问候

#6


1  

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

公共静态更新(值:Object, options: Object): Promise>

check documentation once http://docs.sequelizejs.com/class/lib/model.js~Model.html#static-method-update

检查文档一旦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


65  

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将一个新记录插入到db中。

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

首先,您需要搜索该记录,获取它,只有在此之后更改它的属性并更新它,例如:

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

#2


122  

Since version 2.0.0 you need to wrap your where clause in a where property:

由于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

The latest version actually doesn't use success and error anymore but instead uses then-able promises.

最新版本实际上不再使用成功和错误,而是使用当时可以实现的承诺。

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

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

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

#3


27  

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

 });

#4


8  

I think using UPDATE ... WHERE as explained here and here is a lean approach

我认为使用更新……这里解释了什么,这里有一个精益方法吗

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

#5


4  

This solution is deprecated

不建议使用这个解决方案

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

失败|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

问候

#6


1  

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

公共静态更新(值:Object, options: Object): Promise>

check documentation once http://docs.sequelizejs.com/class/lib/model.js~Model.html#static-method-update

检查文档一旦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]

  })