繁体   English   中英

如何使用 ConditionExpression 更新一个属性值而不影响其他属性 - DynamoDB

[英]How to update one attribute value using ConditionExpression without affecting other attributes - DynamoDB

我需要更新 DynamoDB 表项的属性值。 仅当usersIDs数组与当前用户的用户 ID一致时,重复部分才应更新。

然后我创建了 ConditionExpression 并运行它。

var metricsParams = {
                TableName: table,
                Key:{
                   "metricsID" : metricsID,
                },
                UpdateExpression: "SET fans.orgID = :orgIDNew, fans.orgName = :orgNameNew, fans.noOfGamesPlayed = fans.noOfGamesPlayed + :val, Moment.datePlayed = :dateNew, Moment.monthPlayed = :monthNew, Moment.week = :weekNew, Moment.usersIDs = list_append(Moment.usersIDs, :usersNew), Moment.repeats = list_append(Moment.repeats, :repeateUsers)",
                ConditionExpression: "contains(Moment.repeats, :repeateUsers)",
                ExpressionAttributeValues:{
                    ":orgIDNew": body.team.id,
                    ":orgNameNew": body.team.domain,
                    ":val": 1,
                    ":dateNew" : Moment().format('LL'),
                    ":monthNew" : Moment().format("MMMM"),
                    ":weekNew" : Moment().format('WW'),
                    ":usersNew" : [body.user.id],
                    ":repeateUsers": [body.user.id]
                },
    
                ReturnValues:"UPDATED_NEW"
    
            };
            console.log("Attempting a conditional update...");
            metricsDoc.update(metricsParams, function(err, data) {
            if (err) {
            console.error("Unable to update item. *from id update* Error JSON:", JSON.stringify(err, null, 2));
            } else {
            console.log("UpdateItem succeeded: FROM DYNAMODB METRICS**", JSON.stringify(data, null, 2));

但是当我添加这个 ConditionExpression 时,其他属性也会因此而影响。 那么我该如何解决这个问题。 我需要创建单独的 UpdateExpression 吗?

你是对的。 如果您有多个条件,则需要多个操作。 一个操作可以有 0-1 个条件,这适用于整个操作:

Docs:如果条件表达式为真,则操作成功; 否则,操作失败

鉴于您当前的结构,这里有两个选项:

  1. 进行两次更新操作,一种是无条件的,一种是有条件的。 (注意list_append(Moment.repeats, :repeateUsers)不能防止添加重复条目)
  2. 进行查询以检索当前记录,并在确定需要写入的内容后,进行一次无条件更新操作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM