Reputation: 11
Say I want to add a record like below:
{
id:876876,
username:example,
email:[email protected],
phone:xxxxxxx,
created_at:current_date,
updated_at:current_date
}
What I want is to check with the id if record exist created_date
should not be modified only updated_date
should have current_date
.
Can we do this with put method without having to be making a get item call?
Upvotes: 1
Views: 387
Reputation: 2283
To create a new item or update an existing item with conditional expression. Prefer to use updateItem rather than putItem.
If the Hash key (Primary key) doesn't exist both putItem
and updateItem
create a new record. If the record already exist, putItem
will completely override the existing row but updateItem
only updates the attributes passed in UpdateExpression not a whole record.
In your case, use if_not_exists()
function to check whether the created_at
field already exists or not. If exists created_at
will not be overridden.
Update expression: "SET #email = :email, #created_at = if_not_exists(#created_at, :created_at), #updated_at = :updated_at"
Sample snippet
var params = {
ExpressionAttributeNames: {
"#email": "email",
"#created_at": "created_at",
"#updated_at": "updated_at"
},
ExpressionAttributeValues: {
":email": {
S: "[email protected]"
},
":created_at": {
S: date.toISOString()
},
":updated_at": {
S: date.toISOString()
}
},
Key: {
"id": {
S: "T1"
}
},
ReturnValues: "ALL_NEW",
TableName: "stack",
UpdateExpression: "SET #email = :email, #created_at = if_not_exists(#created_at, :created_at), #updated_at = :updated_at"
};
ddb.updateItem(params, function(err, data) {
if (err) console.log(err, err.stack); // an error occurred
else console.log(data);
})
Upvotes: 1