Reputation: 1384
Here is an example. I am using AWS Lambda function in Node.JS. This is the object in DynamoDB:
{
email: "[email protected]",
name: "John Doe",
score: "12"
}
Now I want to first check what his saved score is. If his current score is more than the score already present in DB then update the DB else leave it as it is. Currently, my code is updating it every time. I'm not sure how to proceed and which function to use.
If his score is 15, then after checking the DB it should update it to:
{
email: "[email protected]",
name: "John Doe",
score: "15"
}
If his score is 7, it should leave it as it is.
{
email: "[email protected]",
name: "John Doe",
score: "12"
}
Edit - The following issue has also been solved. Found a workaround. Still looking for answers. So leaving it open.
Now my issue is that I am using the same function for both updating and creating records. Is that possible?
If a new user plays the game his email, name, and score are saved to the DB. And if an existing user plays, only his score is updated if it is greater than the one in DB.
This is where I'm currently stuck. Getting these 2 issues, 1. name is a reserved keyword. I wonder how was it allowed me to use name as an attribute when i was just using put. 2. email cannot be updated since it is part of key.
Here is my current code,
function addToLeaderBoard(currentScore, email, name){
var params = {
TableName: tablename,
Key: {
"email": email
},
UpdateExpression: "set score = :num, name = :player, email = :mail",
ConditionExpression: "score > :num",
ExpressionAttributeValues: {
":num": currentScore,
":player": name,
":mail": email
},
ReturnValues: "UPDATED_NEW"
};
docClient.update(params, function(err, data) {
if (err) console.log(err);
else console.log(data);
});
}
Upvotes: 3
Views: 8569
Reputation: 8455
What you want to do is a conditional update. This allows you to only the update the item in DynamoDB if a condition is met. In your case that condition would be, that the new score has to be higher than the existing score.
Such a conditional update would look like the following example. Note the ConditionExpression
in there, which is responsible for only updating the item when the condition is met.
'use strict';
const aws = require('aws-sdk');
var newScore = 123;
var docClient = new AWS.DynamoDB.DocumentClient()
var params = {
TableName: "players",
Key: {
"email": "[email protected]"
},
UpdateExpression: "set score = :num",
ConditionExpression: "score > :num",
ExpressionAttributeValues: {
":num": newScore
},
ReturnValues: "UPDATED_NEW"
};
docClient.update(params, function(err, data) {
if (err) console.log(err);
else console.log(data);
}
});
Upvotes: 4