首页 > 解决方案 > node.js AWS dynamodb updateItem 用于可能存在或不存在的多个值

问题描述

我在 nodejs 中使用这个 aws-sdk 来访问/更新 dynamodb 条目。

我有一个很长的文档,如下面的示例所示。

UID = 1
sort_key = abc
variable = X
variable2 = y
variable3 = z
.....
variable(n) = n2

我希望能够从https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB/DocumentClient.html#update-property构建和更新

以便它可以检测是否没有特定变量的值,它不会更新它。

例如,根据要求可能只有变量 2 和 4 的更新,所以我没有其他任何详细信息。

或者我是否正确假设当我检测到输入这些特定值时我必须构建将创建 UpdateExpression 和 ExpressionAttributeValues 的 JavaScript 代码?

如果这就是模式,那么它有点乏味,但我明白了。这就是必须要做的事情。我只是希望有一个优雅的解决方案。

这就是我现在的想法。回应以代码形式提出想法的评论。

'''

            # Above this a load of if statments checking if the value is null. If not the name of the variable is added to the value listofvariables json
            example of json produced after checking all the keys one by one if they are null.
            var obj = { "variable 1": "test", "variable 2": "test2" };
            UpdateExpression = "set"

            for (const key of Object.keys(obj)) {
                    var addMevar =" " + key + " = :" + key + ","
                    var addMevalue = { key : obj[key] }
                    var UpdateExpression = UpdateExpression.concat(addme)
                    var ExpressionAttributeValues = ExpressionAttributeValues.concat(addMevalue)
            }

            var params = {
              TableName: 'Table',
              Key: { HashKey : 'hashkey' },
              UpdateExpression: UpdateExpression
              ExpressionAttributeValues: ExpressionAttributeValues
            };

'''

我真正想要的是这样的东西。

var params = {
                  TableName: 'Table',
                  Key: { HashKey : 'hashkey' },
                  UpdateExpression: all the value here like usual 'set blablabla =something '
                  ExpressionAttributeValues: {value set to the values in the rest of my code. However some flag that says if null you don't update the value in DB as empty.}
                };

最终我知道查询的构建是有效的。我只是希望有人知道更好的方法。

标签: javascriptnode.jsamazon-dynamodbdynamodb-queries

解决方案


唯一的方法是放入构建 JSON 的逻辑。AWS 发电机过滤器无法知道或关心某些内容是否为空而不包含它的条件等。


推荐阅读