Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to update a record using sequelize for node?
    primarykey
    data
    text
    <p>I'm creating a RESTful API with NodeJS, express, express-resource, and Sequelize that is used to manage datasets stored in a MySQL database.</p> <p>I'm trying to figure out how to properly update a record using Sequelize.</p> <p>I create a model:</p> <pre><code>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 } }) } </code></pre> <p>Then, in my resource controller, I define an update action.</p> <p>In here I want to be able to update the record where the id matches a <code>req.params</code> variable.</p> <p>First I build a model and then I use the <code>updateAttributes</code> method to update the record.</p> <pre><code>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 =&gt; { res.json({ success: true }, 200) }) .on('failure', error =&gt; { throw new Error(error) }) } else throw new Error('Data not provided') } </code></pre> <p>Now, this does not actually produce an update query as I would expect.</p> <p>Instead, an insert query is executed:</p> <pre><code>INSERT INTO `Locales`(`id`, `locale`, `createdAt`, `updatedAt`, `visible`) VALUES ('1', 'us', '2011-11-16 05:26:09', '2011-11-16 05:26:15', 1) </code></pre> <p>So my question is: What is the proper way to update a record using Sequelize ORM?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload