附加到列表(如果存在)或在dynamoDB中添加列表 [英] append to list if exist or add list in dynamoDB

查看:61
本文介绍了附加到列表(如果存在)或在dynamoDB中添加列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在DynamoDB中有一个产品表,其中包含一些项目.现在,我需要将买家列表添加到可以增长的产品中,即追加到列表中.它适用于如果我有一个空列表或表项目中包含某些项目的列表,但是对于第一次添加它会引发错误.有什么方法可以检查列表是否存在,然后追加否则添加一个列表.这是我的代码

I have a product table in DynamoDB which has some items. Now I need to add list of buyers to the product which can grow i.e. append to list. It works for if I have an empty list or a list with some items in the table item but for the first addition it throws an error. Is there any way to check if list exists then append else add a list. here is my code

let params = {
    TableName: "product",
    ExpressionAttributeNames: {
        "#Y": "buyer"
    },
    ExpressionAttributeValues: {
        ":y": ["PersonXYZ"]
    },
    Key: {
        id: 'Hy2H4Z-lf'
    },
    UpdateExpression: "SET #Y = list_append(#Y,:y)"
};
updateItemInDDB(params).then((data) => {
    res.status(200).send(data);
}, err => {
    console.log(err);
    res.sendStatus(500);
});

UpdateItemInDDB只是一个接受参数并在其上运行dnamodb代码的函数.我正在通过Document Client使用DynamoDB的javascript sdk.

UpdateItemInDDB is just a function which takes a params and run dnamodb code on it. I am using javascript sdk for DynamoDB with Document Client.

推荐答案

嵌套条件表达式

您可以使用条件属性确实存在的ConditionalExpression运行SET append_list,然后如果失败,则使用条件属性不存在的ConditinalExpression运行SET.

You could run SET append_list with a ConditionalExpression that the attribute does exist, then if that fails run SET with a ConditinalExpression that the attribute does not exist.

let params1 = {
    TableName: "product",
    ExpressionAttributeNames: {
        "#Y": "buyer"
    },
    ExpressionAttributeValues: {
        ":y": ["PersonXYZ"]
    },
    Key: {
        id: 'Hy2H4Z-lf'
    },
    ConditionExpression: "attribute_exists(buyer)",
    UpdateExpression: "SET #Y = list_append(#Y,:y)"
};
updateItemInDDB(params1).then((data) => {
    res.status(200).send(data);
}, err => {
    console.log(err);
    let params2 = {
    TableName: "product",
    ExpressionAttributeNames: {
        "#Y": "buyer"
    },
    ExpressionAttributeValues: {
        ":y": ["PersonXYZ"]
    },
    Key: {
        id: 'Hy2H4Z-lf'
    },
    ConditionExpression: "attribute_not_exists(buyer)",
    UpdateExpression: "SET #Y = (#Y,:y)"
    };
    updateItemInDDB(params2).then((data) => {
    res.status(200).send(data);
    }, err => {
        console.log(err);
        res.sendStatus(500);
    });
});

这篇关于附加到列表(如果存在)或在dynamoDB中添加列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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