Sequelize-更新记录并返回结果



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

无论人员模型是否成功更新,我都不会得到信息。变量结果只是一个包含一个元素的数组,0=1

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

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

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文档:promise返回一个包含一个或两个元素的数组。第一个元素x始终是受影响的行数,而第二个元素y是实际的受影响行(仅在options.returning设置为true的情况下才支持)

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

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

您只需找到项目并更新其属性,然后保存即可。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();

Postgres:

Executing (default): UPDATE "jobs" SET "payload"=$1,"updatedAt"=$2 WHERE "id" = $3
sequelize的Update函数返回许多受影响的行(结果数组的第一个参数)。

您应该致电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);
      });

终于得到了。返回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);
    }); 

});

使用异步等待可以做同样的事情,尤其是避免嵌套Promises您只需要创建异步函数:)

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

还有另一种方法-将findByPk静态方法和update非静态方法一起使用。例如:

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

请注意,此代码必须位于异步函数内部。

您可以先获取要更新的模型,然后对其调用set(),然后调用save()。返回此对象将获得更新后的模型。

虽然这可能不是最短的方法,但我更喜欢它,因为您可以单独处理未找到的错误和更新错误。

const instance = await Model.findOne({
  where: {
    'id': objectId
  }
});
if (instance && instance.dataValues) {
  instance.set('name', objectName);
  return await instance.save(); // promise rejection (primary key violation…) might be thrown here
} else {
  throw new Error(`No Model was found for the id ${objectId}`);
}

如果您使用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()
  }

最新更新