programing

노드의 속편을 사용하여 레코드를 업데이트하려면 어떻게 해야 합니까?

yoursource 2022. 9. 16. 21:18
반응형

노드의 속편을 사용하여 레코드를 업데이트하려면 어떻게 해야 합니까?

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변수.

먼저 모델을 만들고 나서updateAttributesmethod를 선택합니다.

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

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

최신 버전은 실제로 사용하지 않습니다.success그리고.error더 이상 사용하지 않고then- 가능한 약속.

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

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

비동기/대기 사용

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/ #update values-supdate values-supdate-earray affected c

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

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

 });

2020년 1월 답변
이해해야 할 점은 모델에 대한 업데이트 방법과 인스턴스(레코드)에 대한 별도의 업데이트 방법이 있다는 것입니다. Model.update()일치하는 모든 레코드를 업데이트하고 어레이를 반환합니다.속편 크기 설명서를 참조하십시오. Instance.update()는 레코드를 갱신하고 인스턴스 개체를 반환합니다.

따라서 질문당 하나의 레코드를 업데이트하려면 코드는 다음과 같습니다.

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: 'some@email.com',
    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)
})

그럼, 을 사용해 주세요.Model.findOne()또는Model.findByPkId()단일 인스턴스(레코드)를 취득하고 나서Instance.update()

그리고 2018년 12월에 답을 찾고 있는 사람들에게, 약속을 사용하는 올바른 구문은 다음과 같습니다.

Project.update(
    // Values to update
    {
        title:  'a very different title now'
    },
    { // Clause
        where: 
        {
            id: 1
        }
    }
).then(count => {
    console.log('Rows updated ' + count);
});

사용하는 것 같아요.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) 
})

속편에서 레코드를 업데이트할 수 있는 두 가지 방법이 있습니다.

먼저 고유 식별자가 있는 경우 where 구를 사용하거나 동일한 식별자를 사용하여 여러 레코드를 업데이트할 수 있습니다.

업데이트할 개체 전체 또는 특정 열을 생성할 수 있습니다.

const objectToUpdate = {
title: 'Hello World',
description: 'Hello World'
}

models.Locale.update(objectToUpdate, { where: { id: 2}})

특정 열만 업데이트

models.Locale.update({ title: 'Hello World'}, { where: { id: 2}})

둘째, 쿼리를 찾기 위해 Find를 사용하고 set and save 기능을 사용하여 DB를 업데이트할 수 있습니다.


const objectToUpdate = {
title: 'Hello World',
description: 'Hello World'
}

models.Locale.findAll({ where: { title: 'Hello World'}}).then((result) => {
   if(result){
   // Result is array because we have used findAll. We can use findOne as well if you want one row and update that.
        result[0].set(objectToUpdate);
        result[0].save(); // This is a promise
}
})

항상 트랜잭션을 사용하여 업데이트 또는 새 행을 만듭니다. 이렇게 하면 오류가 있거나 여러 업데이트를 수행하는 경우 업데이트가 롤백됩니다.


models.sequelize.transaction((tx) => {
    models.Locale.update(objectToUpdate, { transaction: tx, where: {id: 2}});
})

이 솔루션은 권장되지 않습니다.

fail | fail | error()는 권장되지 않으며 2.1에서 삭제됩니다.대신 약속 스타일을 사용하십시오.

그래서 너는 그것을 사용해야 한다.

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() 부탁드립니다.

안부 전해요

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

비동기/대기 시:

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

public static 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]

  })

최신 Javascript Es6에서 비동기 및 대기 사용

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

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

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

모델에서 특정 필드 값을 늘리는 방법을 찾는 경우...

가 있었다.sequelize@5.21.3

User.increment("field", {by: 1, where: {id: 1});

참조: https://github.com/sequelize/sequelize/issues/7268

레코드를 갱신하는 것은 매우 간단합니다.

  1. 속편에서 ID(또는 원하는 것)로 레코드를 찾습니다.
  2. 을 넘깁니다.result.feild = updatedField
  3. 레코드가 데이터베이스 속편에 포함되지 않으면 패러머로 새 레코드를 만듭니다.
  4. V4의 모든 버전에 대해 코드 #1 테스트에 대한 자세한 내용은 예제를 참조하십시오.
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)
    });

업데이트 방법을 사용하여 기록을 업데이트했습니다.

  1. models는 모델이 배치되어 있는 .timeout 파일입니다.
  2. users는 모델명입니다.
  3. 업데이트는 속편에 의해 제공되는 내장 기능입니다.
  4. ID가 1인 사용자 테이블에 이름과 도시를 업데이트하고 있습니다.
models.users.update({
 "name":'sam',
 "city":'USA'
},
where:{ id:1}
)

사용한 적이 있다sequelize.js,node.js ★★★★★★★★★★★★★★★★★」transaction수 ID를를 찾을 수 없다는 를 발생시킵니다.데이터를 찾을 수 없는 경우 해당 ID를 가진 데이터를 찾을 수 없는 에러가 발생합니다.

editLocale: async (req, res) => {

    sequelize.sequelize.transaction(async (t1) => {

        if (!req.body.id) {
            logger.warn(error.MANDATORY_FIELDS);
            return res.status(500).send(error.MANDATORY_FIELDS);
        }

        let id = req.body.id;

        let checkLocale= await sequelize.Locale.findOne({
            where: {
                id : req.body.id
            }
        });

        checkLocale = checkLocale.get();
        if (checkLocale ) {
            let Locale= await sequelize.Locale.update(req.body, {
                where: {
                    id: id
                }
            });

            let result = error.OK;
            result.data = Locale;

            logger.info(result);
            return res.status(200).send(result);
        }
        else {
            logger.warn(error.DATA_NOT_FOUND);
            return res.status(404).send(error.DATA_NOT_FOUND);
        }
    }).catch(function (err) {
        logger.error(err);
        return res.status(500).send(error.SERVER_ERROR);
    });
},

이렇게 했어요.

Model.findOne({
    where: {
      condtions
    }
  }).then( j => {
    return j.update({
      field you want to update
    }).then( r => {
      return res.status(200).json({msg: 'succesfully updated'});
    }).catch(e => {
      return res.status(400).json({msg: 'error ' +e});
    })
  }).catch( e => {
    return res.status(400).json({msg: 'error ' +e});
  });

ifModel.update스테이트먼트가 기능하지 않는 경우는, 다음과 같이 시험할 수 있습니다.

try{ 
    await sequelize.query('update posts set param=:param where conditionparam=:conditionparam', {replacements: {param: 'parameter', conditionparam:'condition'}, type: QueryTypes.UPDATE})
}
catch(err){
    console.log(err)
}
var whereStatement = {};

  whereStatement.id = req.userId;

  if (whereStatement) {
    User.findOne({
      where: whereStatement
    })
      .then(user => {

        if (user) {
          
          var updateuserdetails = {
            email: req.body.email,
            mobile: req.body.mobile,
            status: req.body.status,
            user_type_id: req.body.user_type_id
          };

          user.update(
            updateuserdetails
          )
            .then(function () {
              res.status(200).send({ message: 'Success...' });
            })
            .catch(err => {
              res.status(500).send({ message: err.message });
            });
        }

        
      })

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

반응형