我正在尝试更新作为字符串列表的项目属性。 只有当属性不存在时,我才能更新(追加)该属性吗? 有点像 list_append & if_not_exists。
var params = { ...
UpdateExpression:
'SET friends = list_append(if_not_exists(friends, :empty_list), :new_friend)',
ExpressionAttributeValues:{ ":new_friend": [{"S":"Bobo"}], ":empty_list" :[] } };
这不行,有什么办法吗? 所以如果 Bobo 仍然不在我的“ friend ”列表中,它将附加它
最佳答案
您可以根据您的要求使用“不包含”和“list_append”。
如果 friend 不在列表中,下面的代码会将新 friend 插入到列表中。
如果好友已经存在于列表中,它会抛出“条件请求失败”。
条件失败时的错误消息:-
Unable to update item. Error JSON: {
"message": "The conditional request failed",
"code": "ConditionalCheckFailedException",
"time": "2016-06-22T08:18:36.483Z",
"requestId": "86805965-240b-43e0-8fdc-77fb9ae1b15c",
"statusCode": 400,
"retryable": false,
"retryDelay": 0
}
下面的代码工作正常。已经测试成功。
代码示例:
var AWS = require("aws-sdk");
AWS.config.update({
region : "us-west-2",
endpoint : "http://localhost:8000"
});
var docClient = new AWS.DynamoDB.DocumentClient();
var table = "users";
var userid = 1;
var friendId = ["f4"];
var friendIdStr = "f4";
//Add the new DOCUMENT TYPE attribute to the table
var params = {
TableName : table,
Key: {
"id" : userid
},
"UpdateExpression": "set friends = list_append (friends, :friendId)",
"ConditionExpression": "not contains (friends, :friendIdStr)",
"ExpressionAttributeValues": {
":friendId": friendId,
":friendIdStr" : friendIdStr
},
"ReturnValues" : "UPDATED_NEW"
};
console.log("Updated an item...");
docClient.update(params, function(err, data) {
if (err) {
console.error("Unable to update item. Error JSON:", JSON.stringify(err,
null, 2));
} else {
console.log("Updated item:", JSON.stringify(data, null, 2));
}
});
关于javascript - 将不存在的元素添加到 DynamoDB 中的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37910150/