Sequelize - 更新记录,并返回结果 [英] Sequelize - update record, and return result

查看:2582
本文介绍了Sequelize - 更新记录,并返回结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用MySQL的sequelize。例如,如果我这样做:

I am using sequelize with MySQL. For example if I do:

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);
    });

如果人员模型已成功更新,我无法获取信息。变量结果只是一个包含一个元素的数组,0 = 1

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

我怎么能确定记录是否已更新。

How can I know for certain that the record was updated or not.

推荐答案

以下是我认为您正在寻找的内容。

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
});

来自Sequelize docs
promise返回一个包含一个或两个元素的数组。第一个元素 x 始终是受影响的行数,而第二个元素 y 是实际受影响的行(仅postgres支持 options.returning 设置为 true 。)

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.)

假设您使用的是Postgres,您可以使用 result [1] .dataValues 访问更新的对象。

Assuming you are using Postgres, you can access the updated object with result[1].dataValues.

你必须设置 return:true 选项告诉Sequelize返回对象。 plain:true 只是返回对象本身,而不是其他可能没用的混乱元数据。

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.

这篇关于Sequelize - 更新记录,并返回结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆