在DynamoDB中将非现有元素添加到数组中

Ale*_*noy 4 javascript node.js amazon-dynamodb

我试图更新作为字符串列表的项属性.只有在属性不存在时才能更新(追加)属性.list_append和if_not_exists的种类.

var params = {...

UpdateExpression: 
Run Code Online (Sandbox Code Playgroud)

'SET friends = list_append(if_not_exists(friends,:empty_list),:new_friend)',

ExpressionAttributeValues:{
    ":new_friend": [{"S":"Bobo"}],
    ":empty_list" :[]
 } };
Run Code Online (Sandbox Code Playgroud)

这不行,有办法吗?因此,如果Bobo仍然不在我的"朋友"列表中,它会附加它

not*_*est 8

您可以根据需要使用"not contained""list_append".

如果朋友尚未出现在列表中,则下面的代码会将新朋友列入列表.

如果朋友已经出现在列表中,则会抛出"条件请求失败".

条件失败时出现错误信息: -

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
}
Run Code Online (Sandbox Code Playgroud)

以下代码工作正常.它已经成功测试过.

代码示例:

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));
    }
});
Run Code Online (Sandbox Code Playgroud)

  • 只是为了未来读者的一个精度:`list_append()` 函数的参数必须是数组,所以要注意 `friendId` 变量的类型(`varfriendId = ["f4"]`)。 (3认同)