a_a*_*ias 94 mysql node.js express sequelize.js
我正在使用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
},
locale: {
type: DataTypes.STRING,
allowNull: false,
unique: true,
validate: {
len: 2
}
},
visible: {
type: DataTypes.BOOLEAN,
defaultValue: 1
}
})
}
Run Code Online (Sandbox Code Playgroud)
然后,在我的资源控制器中,我定义了一个更新操作.
在这里,我希望能够更新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')
}
Run Code Online (Sandbox Code Playgroud)
现在,这实际上并没有像我期望的那样产生更新查询.
而是执行插入查询:
INSERT INTO `Locales`(`id`, `locale`, `createdAt`, `updatedAt`, `visible`)
VALUES ('1', 'us', '2011-11-16 05:26:09', '2011-11-16 05:26:15', 1)
Run Code Online (Sandbox Code Playgroud)
所以我的问题是:使用Sequelize ORM更新记录的正确方法是什么?
kub*_*ube 183
从版本2.0.0开始,您需要将where子句包装在where属性中:
Project.update(
{ title: 'a very different title now' },
{ where: { _id: 1 } }
)
.success(result =>
handleResult(result)
)
.error(err =>
handleError(err)
)
Run Code Online (Sandbox Code Playgroud)
最新版本实际上不再使用success,error而是使用then-able promises.
所以上面的代码看起来如下:
Project.update(
{ title: 'a very different title now' },
{ where: { _id: 1 } }
)
.then(result =>
handleResult(result)
)
.catch(err =>
handleError(err)
)
Run Code Online (Sandbox Code Playgroud)
ale*_*lex 92
我没有使用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 () {})
}
})
Run Code Online (Sandbox Code Playgroud)
Far*_*arm 33
从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
});
Run Code Online (Sandbox Code Playgroud)
Lau*_*bba 33
2020 年 1 月答案
要理解的是,模型有一个更新方法,实例(记录)有一个单独的更新方法。 Model.update()更新所有匹配的记录并返回一个数组,请参阅 Sequelize 文档。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)
})
Run Code Online (Sandbox Code Playgroud)
因此,使用Model.findOne()或Model.findByPkId()获取单个实例(记录)的句柄,然后使用Instance.update()
Don*_*ong 19
对于在2018年12月寻找答案的人来说,这是使用promises的正确语法:
Project.update(
// Values to update
{
title: 'a very different title now'
},
{ // Clause
where:
{
id: 1
}
}
).then(count => {
console.log('Rows updated ' + count);
});
Run Code Online (Sandbox Code Playgroud)
Has*_*sef 10
我认为使用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)
})
Run Code Online (Sandbox Code Playgroud)
有两种方法可以更新 sequelize 中的记录。
首先,如果你有一个唯一的标识符,那么你可以使用 where 子句,否则如果你想用相同的标识符更新多个记录。
您可以创建要更新的整个对象或特定列
const objectToUpdate = {
title: 'Hello World',
description: 'Hello World'
}
models.Locale.update(objectToUpdate, { where: { id: 2}})
Run Code Online (Sandbox Code Playgroud)
仅更新特定列
models.Locale.update({ title: 'Hello World'}, { where: { id: 2}})
Run Code Online (Sandbox Code Playgroud)
其次,您可以使用查找查询来查找它并使用设置和保存功能来更新数据库。
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
}
})
Run Code Online (Sandbox Code Playgroud)
在更新或创建新行时始终使用事务。这样,如果出现任何错误或您进行任何多次更新,它将回滚任何更新:
models.sequelize.transaction((tx) => {
models.Locale.update(objectToUpdate, { transaction: tx, where: {id: 2}});
})
Run Code Online (Sandbox Code Playgroud)
不推荐使用此解决方案
fail | fail | error()已弃用,将在2.1中删除,请改用promise-style.
所以你必须使用
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 !");
})
Run Code Online (Sandbox Code Playgroud)
你也可以使用
.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
}
Run Code Online (Sandbox Code Playgroud)
使用 .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
})
Run Code Online (Sandbox Code Playgroud)