javascript – Incrementing DynamoDB value using AWS SDK v3
I’m attempting to migrate my v2 Lambdas to v3, and I’m having some trouble incrementing a value. Here’s my v2 method:
const params = {
TableName: process.env.USER_TABLE_NAME!,
Key: { UID },
UpdateExpression: 'SET #numRatings = #numRatings + :increment',
ExpressionAttributeNames: {
'#numRatings': 'numRatings'
},
ExpressionAttributeValues: {
':increment': 1
},
ReturnValues: 'ALL_NEW'
};
return await DB.update(params).promise();
v3 method:
const params = {
TableName: process.env.USER_TABLE_NAME!,
Key: {
UID
},
UpdateExpression: 'set numRatings = numRatings + :increment',
ExpressionAttributeValues: {
':increment': 1
},
ReturnValues: 'ALL_NEW'
} as unknown as UpdateItemCommandInput;
try {
const response = await dbClient.send(new UpdateItemCommand(params));
console.log('response', response);
} catch (error) {
console.error('error', error);
}
I’m using TypeScript and VS Code gives this error:
Types of property 'Key' are incompatible.
Type '{ UID: string; }' is not comparable to type '{ [key: string]: AttributeValue; }'.
Property 'UID' is incompatible with index signature.
Type 'string' is not comparable to type 'AttributeValue'
CloudWatch gives this unhelpful error:
Cannot read property ‘0’ of undefined
I’m really confused as, as far as I can tell I have followed the documentation properly, their equivalent of “params” is defined as so:
export const params = {
TableName: "TABLE_NAME",
Key: {
primaryKey: "VALUE_1", // For example, 'Season': 2.
sortKey: "VALUE_2", // For example, 'Episode': 1; (only required if table has sort key).
},
// Define expressions for the new or updated attributes
UpdateExpression: "set ATTRIBUTE_NAME_1 = :t, ATTRIBUTE_NAME_2 = :s", // For example, "'set Title = :t, Subtitle = :s'"
ExpressionAttributeValues: {
":t": "NEW_ATTRIBUTE_VALUE_1", // For example ':t' : 'NEW_TITLE'
":s": "NEW_ATTRIBUTE_VALUE_2", // For example ':s' : 'NEW_SUBTITLE'
},
ReturnValues: "ALL_NEW"
};
My apologies if that’s too many code examples but I wanted to be thorough. UID is a string. Thank you in advance for any help
Read more here: Source link