javascript - node.js AWS dynamodb updateItem 用于可能存在或不存在的多个值
问题描述
我在 nodejs 中使用这个 aws-sdk 来访问/更新 dynamodb 条目。
我有一个很长的文档,如下面的示例所示。
UID = 1
sort_key = abc
variable = X
variable2 = y
variable3 = z
.....
variable(n) = n2
以便它可以检测是否没有特定变量的值,它不会更新它。
例如,根据要求可能只有变量 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.}
};
最终我知道查询的构建是有效的。我只是希望有人知道更好的方法。
解决方案
唯一的方法是放入构建 JSON 的逻辑。AWS 发电机过滤器无法知道或关心某些内容是否为空而不包含它的条件等。
推荐阅读
- python - 在 csv 中保存数据框时将时间戳添加到文件名
- javascript - React-Native:通过单击按钮加载屏幕
- validation - 三维向量的 z 分量
- spring-boot - Spring session,控制台消息解读
- oracle - 调用函数时出现“java.sql.SQLException:索引处缺少 IN 或 OUT 参数:: 1”
- python - 锁定窗口一次后,Python 键盘模块 add_hotkey 不起作用。需要帮助
- c# - 是什么导致材料闪烁?
- ruby - 将句子的每个单词转换为字符串(Ruby on Rails)
- amazon-web-services - 仅在具有特定标签的资源上允许 iam:UpdateUser
- neo4j - Neo4j - Flight Analyzer - 2 个问题