javascript - 将不存在的元素添加到 DynamoDB 中的数组

标签 javascript node.js amazon-dynamodb

我正在尝试更新作为字符串列表的项目属性。 只有当属性不存在时,我才能更新(追加)该属性吗? 有点像 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/

相关文章:

javascript - Highcharts 列的日期时间标签

node.js - 如何限制服务器使其仅允许 SSH、与外部 RabbitMQ 服务器的连接以及与外部 MongoDB 服务器的连接?

amazon-dynamodb - 校准 DynamoDB 表的吞吐量

javascript - 停止 Spinner.js

javascript - 什么叫没有服务器端的纯 JavaScript 独立(网络)应用程序?

javascript - 从另一个文件导入的 JSON 包含未定义

node.js - lrange 返回 false 而不是列表

javascript - 我来自 Node 的数据没有绑定(bind)到模板变量

amazon-web-services - AWS : Trigger event if DynamoDB table row is not updated in the last 30 minutes

mongodb - DynamoDB vs ElasticSearch vs S3 - 哪种服务用于超快获取/放置 10-20MB 文件?