gpt4 book ai didi

node.js - 为什么我的属性不存在的条件表达式在 dynamodb 中失败

转载 作者:行者123 更新时间:2023-12-05 04:47:55 24 4
gpt4 key购买 nike

我的 DynamoDB 表有一个主键作为 id相同的id将用于查询一条记录。

现在我想插入一条以idoriginalURL为属性的记录,当且仅当id时我想插入这条记录并且表中不存在 originalURL

更新:- ConditionExpression: "attribute_not_exists(id) AND attribute_not_exists(originalURL)" 仅在主键上下文中有效,according to docs (你可以执行一个有条件的put操作(如果指定的主键不存在则添加一个新项) ,所以attribute_not_exists(originalURL)是否存在没有区别。所以我需要一个解决方案,其中两个条件都有效,或者 originalURL 也充当 key

router.post('/', async function (req, res, next) {

urlId = await nanoid(8);


//const hashids = new Hashids('this is my salt')
//urlId=hashids.encode(1)
console.log('jatin', urlId);
// urlId=uuidv4();

const { longURL } = req.body

const params = {
TableName: 'url',
Item: {
"id": urlId,
"originalURL": longURL
},
UpdateExpression: "set originalURL = :y",
ConditionExpression: "attribute_not_exists(id) AND attribute_not_exists(originalURL)"
}
dynamoDb.put(params, (error, data) => {
if (error) {
console.log(error);
res.status(400).json({ error: error });
} else if (Object.keys(data).length === 0 && data.constructor === Object) {
res.status(200).json(
{
urlId,
longURL,
status: 'success'
})
}

else {
res.status(400).json({ error: 'Please try again' });
}
})
});

截至目前,即使我尝试使用已经存在的相同原始 URL 发送请求,它也会成功添加我不想要的记录。

最佳答案

对于 putItem api,您可以使用条件表达式。根据Doc

ConditionExpression

A condition that must be satisfied in order for aconditional PutItem operation to succeed.

An expression can contain any of the following:

Functions: attribute_exists | attribute_not_exists | attribute_type |contains | begins_with | size

These function names are case-sensitive.

Comparison operators: = | <> | < | > | <= | >= | BETWEEN | IN

Logical operators: AND | OR | NOT

For more information on condition expressions, see ConditionExpressions in the Amazon DynamoDB Developer Guide.

Type: String

Required: No

此文档中也解释了相同的场景:https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.ConditionExpressions.html#Expressions.ConditionExpressions.PreventingOverwrites

The PutItem operation overwrites an item with the same key (if itexists). If you want to avoid this, use a condition expression. Thisallows the write to proceed only if the item in question does notalready have the same key.

aws dynamodb put-item \
--table-name ProductCatalog \
--item file://item.json \
--condition-expression "attribute_not_exists(Id)"

关于node.js - 为什么我的属性不存在的条件表达式在 dynamodb 中失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68284588/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com