私は、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 を使用してレコードを更新する適切な方法は何ですか?
ベストアンサー1
バージョン2.0.0以降では、どこプロパティ内の句where
:
Project.update(
{ title: 'a very different title now' },
{ where: { _id: 1 } }
)
.success(result =>
handleResult(result)
)
.error(err =>
handleError(err)
)
2016-03-09 更新
最新バージョンでは、実際にはsuccess
and は使用されなくなりerror
、代わりにthen
-able promise が使用されます。
したがって、上のコードは次のようになります。
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)
}