您可以使用“不包含” and “列表追加”为了您的要求。
如果好友尚未出现在列表中,以下代码会将新好友插入到列表中。
如果好友已经存在于列表中,则会抛出“条件请求失败”。
如果条件失败,则会出现错误消息:-
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));
}
});