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

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

本文介绍了如何使用节点的续集更新记录?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



我试图找出如何使用Sequelize正确更新记录。



我创建了一个模型:

  module.exports = function(Sequelize,DataTypes){
return sequelize.define('Locale',{
id:{
type:DataTypes.INTEGER,
autoIncrement:true,
primaryKey:true
},
语言环境:{
类型:DataTypes.STRING,
allowNull:false,
唯一:true,
validate:{
len:2
}
},
visible:{
type:DataTypes.BOOLEAN,
defaultValue:1
}
})
}

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



在这里我想能够更新记录,其中id匹配一个 r首先我建立一个模型,然后我使用 updateAttributes 方法来更新记录。

  const Sequelize = require('sequelize')
const {dbconfig} = require ('../config.js')

//初始化数据库连接
const sequelize = new Sequelize(dbconfig.database,dbconfig.username,dbconfig.password)

//语言环境模型
const Locales = sequelize.import(__ dirname +'./models/Locale')

//如果需要,可以创建模式
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 => {
抛出新错误(错误)
})
}
else
抛出新错误('数据未提供')
}

现在,这并不实际产生一个我所期望的更新查询。



而是执行插入查询:

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



首先你需要搜索记录,抓取它,只有在其属性和之后才能更改它,例如:

  Project.find({where:{title:'aProject'}})
.on(' ,function(project){
//检查db
中是否存在记录if(project){
project.updateAttributes({
title:'a very different title now'
})
.success(function(){})
}
})


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

I'm trying to figure out how to properly update a record using 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.

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

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?

解决方案

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.

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

这篇关于如何使用节点的续集更新记录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-26 05:39