code

Sequelize for Node를 사용하여 레코드를 업데이트하는 방법은 무엇입니까?

codestyles 2020. 9. 4. 07:29
반응형

Sequelize for Node를 사용하여 레코드를 업데이트하는 방법은 무엇입니까?


MySQL 데이터베이스에 저장된 데이터 세트를 관리하는 데 사용되는 NodeJS, express, express-resource 및 Sequelize로 RESTful API를 만들고 있습니다.

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을 사용하여 레코드를 업데이트하는 적절한 방법은 무엇입니까?


나는 Sequelize를 사용하지 않았지만 설명서를 읽은 후 새 객체를 인스턴스화하고 있음이 분명하므로 Sequelize가 새 레코드를 db에 삽입합니다.

먼저 해당 레코드를 검색하고 가져 와서 속성을 변경하고 업데이트 해야합니다. 예를 들면 다음과 같습니다.

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

버전 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-03-09 업데이트

최신 버전은 실제로 사용하지 않는 successerror더 이상 대신 사용 then-able 약속을.

따라서 상단 코드는 다음과 같습니다.

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

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


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

 });

그리고 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);
});

내가 사용 생각 UPDATE ... WHERE설명한 바와 같이 여기여기하는 것은 린 (lean) 방식이다

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

이 솔루션은 더 이상 사용되지 않습니다.

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()뿐만 아니라

문안 인사


현대 자바 스크립트 Es6에서 비동기 및 대기 사용

const title = "title goes here";
const id = 1;

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

결과를 반환 할 수 있습니다 ...


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

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]

  })

Model.update () 메서드를 사용할 수 있습니다.

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
}

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

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

참고URL : https://stackoverflow.com/questions/8158244/how-to-update-a-record-using-sequelize-for-node

반응형