Javascript Sequelize - 更新记录,并返回结果
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38524938/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Sequelize - update record, and return result
提问by Vedran Maricevic.
I am using sequelize with MySQL. For example if I do:
我在 MySQL 中使用 sequelize。例如,如果我这样做:
models.People.update({OwnerId: peopleInfo.newuser},
{where: {id: peopleInfo.scenario.id}})
.then(function (result) {
response(result).code(200);
}).catch(function (err) {
request.server.log(['error'], err.stack);
).code(200);
});
I am not getting information back if the people model was succesfully updated or not. Variable result is just an array with one element, 0=1
无论人员模型是否成功更新,我都不会收到信息。变量结果只是一个只有一个元素的数组,0=1
How can I know for certain that the record was updated or not.
我如何确定该记录是否已更新。
回答by nickang
Here's what I think you're looking for.
这就是我认为您正在寻找的内容。
db.connections.update({
user: data.username,
chatroomID: data.chatroomID
}, {
where: { socketID: socket.id },
returning: true,
plain: true
})
.then(function (result) {
console.log(result);
// result = [x] or [x, y]
// [x] if you're not using Postgres
// [x, y] if you are using Postgres
});
From Sequelize docs:
The promise returns an array with one or two elements. The first element x
is always the number of affected rows, while the second element y
is the actual affected rows (only supported in postgres with options.returning
set to true
.)
来自 Sequelize文档:承诺返回一个包含一两个元素的数组。第一个元素x
始终是受影响的行数,而第二个元素y
是实际受影响的行(仅在 postgres 中支持并options.returning
设置为true
.)
Assuming you are using Postgres, you can access the updated object with result[1].dataValues
.
假设您使用的是 Postgres,您可以使用result[1].dataValues
.
You must set returning: true
option to tell Sequelize to return the object. And plain: true
is just to return the object itself and not the other messy meta data that might not be useful.
您必须设置returning: true
选项以告诉 Sequelize 返回对象。并且plain: true
只是返回对象本身而不是其他可能没有用的杂乱元数据。
回答by Tilekbekov Yrysbek
Update function of sequelize returns a number of affected rows (first parameter of result array).
sequelize 的更新函数返回受影响的行数(结果数组的第一个参数)。
You should call find to get updated row
您应该调用 find 以获取更新的行
models.People.update({OwnerId: peopleInfo.newuser},
{where: {id: peopleInfo.scenario.id}})
.then(() => {return models.People.findById(peopleInfo.scenario.id)})
.then((user) => response(user).code(200))
.catch((err) => {
request.server.log(['error'], err.stack);
});
回答by David Dehghan
You can just find the item and update its properties and then save it. The save() results in a UPDATE query to the db
您只需找到该项目并更新其属性,然后保存即可。save() 导致对数据库的 UPDATE 查询
const job = await Job.findOne({where: {id, ownerId: req.user.id}});
if (!job) {
throw Error(`Job not updated. id: ${id}`);
}
job.name = input.name;
job.payload = input.payload;
await job.save();
On Postgres:
在 Postgres 上:
Executing (default): UPDATE "jobs" SET "payload"=,"updatedAt"= WHERE "id" =
回答by Bharat Suryawanshi
same thing you can do with async-await, especially to avoid nested Promises You just need to create async function :)
你可以用 async-await 做同样的事情,特别是为了避免嵌套的 Promises 你只需要创建 async 函数:)
const asyncFunction = async function(req, res) {
try {
//update
const updatePeople = await models.People.update({OwnerId: peopleInfo.newuser},
{where: {id: peopleInfo.scenario.id}})
if (!updatePeople) throw ('Error while Updating');
// fetch updated data
const returnUpdatedPerson = await models.People.findById(peopleInfo.scenario.id)
if(!returnUpdatedPerson) throw ('Error while Fetching Data');
res(user).code(200);
} catch (error) {
res.send(error)
}
}
回答by Anoop P S
Finally i got it. returning true wont work in mysql , we have to use findByPk in order hope this code will help.
最后我明白了。返回 true 在 mysql 中不起作用,我们必须使用 findByPk 以希望此代码会有所帮助。
editUser:(root, {id, params}, args, context ) => {
return new Promise(function(resolve, reject) {
Users.update({
subject: params.firstName, body: params.lastName, status: params.status
},{
returning:true,
where: {id:id }
}).then(function(){
var user = Users.findByPk(id);
resolve(user);
});
}).then(function(result, affected){
return result.dataValues;
});
},
回答by Basanta Kc
If you're using postgres and updating one row.
如果您使用 postgres 并更新一行。
try {
const result = await MODELNAME.update(req.body, {
where: { id: req.params.id },
returning: true
});
if (!result) HANDLEERROR()
const data = result[1][0].get();
res.status(200).json({ success: true, data });
} catch (error) {
HANDLEERROR()
}
回答by ns16
There is another way - use findByPk static method and update not-static method together. For example:
还有另一种方法 - 一起使用 findByPk 静态方法和更新非静态方法。例如:
let person = await models.People.findByPk(peopleInfo.scenario.id);
if (!person) {
// Here you can handle the case when a person is not found
// For example, I return a "Not Found" message and a 404 status code
}
person = await person.update({ OwnerId: peopleInfo.newuser });
response(person).code(200);
Note this code must be inside an asynchronous function.
请注意,此代码必须位于异步函数内。