将不存在的元素添加到 DynamoDB 中的数组 [英] Add non existing element to array in DynamoDB

查看:30
本文介绍了将不存在的元素添加到 DynamoDB 中的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试更新作为字符串列表的 items 属性.仅当属性不存在时,我可以更新(附加)属性吗?list_append & 的种类if_not_exists.

Im trying to update items attribute that is a list of strings. Can I update (append) the attribute only if it not exist . Kind of list_append & if_not_exists.

var 参数 = { ...

var params = { ...

UpdateExpression: 

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

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

ExpressionAttributeValues:{
    ":new_friend": [{"S":"Bobo"}],
    ":empty_list" :[]
 } };

这行不通,有什么办法吗?所以如果 Bobo 仍然不在我的朋友"列表中,它会附加它

this is not working, is there a way? so if Bobo still not in my "friends" list it will append it

推荐答案

您可以使用 "not contains""list_append" 来满足您的要求.

You can use the "not contains" and "list_append" for your requirement.

如果新朋友不在列表中,则以下代码会将新朋友插入列表.

The below code inserts the new friend to list if the friend is NOT already present in the list.

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

If the friend is already present in the list, it would throw "conditional request failed".

条件失败时的错误消息:-

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
}

以下代码可以正常工作.已经测试成功了.

The below code works fine. It has been tested successfully.

代码示例:

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));
    }
});

这篇关于将不存在的元素添加到 DynamoDB 中的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆