在DynamoDB中将非现有元素添加到数组中 [英] Add non existing element to array in DynamoDB

查看:380
本文介绍了在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 params = {...

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

推荐答案

你可以使用不包含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天全站免登陆