Reputation: 2356
I am trying to save an answer to a web-quiz into DynamoDB table. Every time answer is submitted, eventually code below will be called. Eg. for 3 answers it will be called 3 times.
Each time answer is added, field UpdatedAt
is updated with current timestamp. This allows me to know when was the last answer submitted. However I also want to know when the first answer was submitted and thus I need CreatedAt
field as well. I wonder how this can be implemented?
(I was checking ConditionalCheckExpression
, but it seems to apply to the whole update operation. Whereas I need to find a way to update CreatedAt
only when the item is first inserted).
const now = new Date();
let updateParams = {
TableName: process.env.TABLE_RESULTS,
Key: {
QuizId: '' + quiz_id,
SessionId: '' + session_key,
},
UpdateExpression: `SET #QQ_ID = :answer, #updatedAt = :updatedAt`,
ExpressionAttributeNames: {
'#QQ_ID' : `QQ_${question_id}`,
'#updatedAt': 'UpdatedAt',
},
ExpressionAttributeValues: {
':answer': answer,
':updatedAt' : now.toISOString(),
}
};
let result = await doc.update(updateParams).promise();
Upvotes: 6
Views: 7634
Reputation: 3029
Take a look in AWS docs.
SET - Adds one or more attributes and values to an item. If any of these attribute already exist, they are replaced by the new values. You can also use SET to add or subtract from an attribute that is of type Number. For example: SET myNum = myNum + :val
SET supports the following functions:
if_not_exists (path, operand) - if the item does not contain an attribute at the specified path, then if_not_exists evaluates to operand; otherwise, it evaluates to path. You can use this function to avoid overwriting an attribute that may already be present in the item.
list_append (operand, operand) - evaluates to a list with a new element added to it. You can append the new element to the start or the end of the list by reversing the order of the operands.
// use if_not_exists()
UpdateExpression: `SET #QQ_ID = :answer, #updatedAt = :updatedAt, #createdAt = if_not_exists(#createdAt, :createdAt)`,
ExpressionAttributeNames: {
'#QQ_ID' : `QQ_${question_id}`,
'#updatedAt': 'UpdatedAt',
'#createdAt': 'CreatedAt',
},
ExpressionAttributeValues: {
':answer': answer,
':updatedAt' : now.toISOString(),
':createdAt' : now.toISOString(),
}
Upvotes: 10