Sequelize - 更新记录,并返回结果

Ved*_*ic. 39 javascript sequelize.js

我正在使用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);
    });
Run Code Online (Sandbox Code Playgroud)

如果人员模型已成功更新,我不会收到信息.变量结果只是一个包含一个元素的数组,0 = 1

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

nic*_*ang 72

这就是我认为你在寻找的东西.

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
});
Run Code Online (Sandbox Code Playgroud)

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

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

您必须设置returning: true选项以告知Sequelize返回对象.并且plain: true只是返回对象本身而不是其他可能没用的混乱元数据.

  • 我无法使它与MySql一起使用.我猜这只是Postgresql功能:( (4认同)
  • 另外,尽管文档说了什么,我还是将“ undefined”作为第一个参数,并将_受影响的行数_作为第二个参数(使用sqlite)。为了解决这个问题,我在处理任何东西之前做了`result = result.filter(Boolean);`。 (3认同)

Til*_*bek 11

sequelize的更新功能返回一些受影响的行(结果数组的第一个参数).

您应该调用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);
      });
Run Code Online (Sandbox Code Playgroud)

  • 所以似乎唯一的方法是在更新后立即调用 find ? (4认同)
  • 你可以先调用`find`函数,然后使用这个对象进行更新而不使用`where` (3认同)
  • 如果您使用 PostgreSQL,您可以将“returning”选项定义为“true”,以返回受影响的行 (2认同)

Ano*_*P S 6

最后我明白了。返回 true 在 mysql 中不起作用,我们必须使用 findByPk 以希望此代码会有所帮助。

       return new Promise(function(resolve, reject) {
User.update({
        subject: params.firstName, body: params.lastName, status: params.status
    },{
        returning:true,
        where: {id:id }                             
    }).then(function(){
        let response = User.findById(params.userId);                      
        resolve(response);
    }); 
Run Code Online (Sandbox Code Playgroud)

});


Dav*_*han 5

您可以找到该项目并更新其属性,然后保存。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();
Run Code Online (Sandbox Code Playgroud)

在Postgres上:

Executing (default): UPDATE "jobs" SET "payload"=$1,"updatedAt"=$2 WHERE "id" = $3
Run Code Online (Sandbox Code Playgroud)

  • 这需要 2 个查询而不是 1 个 (7认同)
  • 这是通用的最干净的解决方案。谢谢。 (2认同)