Disclaimer: This is not my original idea. Please refer to this link for the AWS documentation segment that I want to introduce here.
How do I update an item in dynamoDB Table?
First of all, you can sign in to AWS directly and update an item. In this blog post, we will do this task from visual studio code (or whatever editor you use) and node.
Example, let's say we would like to update a movie item from:
{
year: 2015,
title: "The Big New Movie",
info: {
plot: "Nothing happens at all.",
rating: 0
}
}
to:
{
year: 2015,
title: "The Big New Movie",
info: {
plot: "Everything happens all at once.",
rating: 5.5,
actors: ["Larry", "Moe", "Curly"]
}
}
To do that, we need to first find the item from AWS database (dynamoDB) and communicate to this service that that is the item we are updating. Let's see how AWS-SDK* achieves this.
/**
* Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* This file is licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License. A copy of
* the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
var AWS = require("aws-sdk");
//Don't forget to configure your AWS credential.
//Endpoint should be "https://[AWS_SERVICE_NAME].[AWS_REGION].amazonaws.com"
//Question: What would happen if aws_region in endpoint and configuration do not match? Which one would take precedence over others?
AWS.config.update({
region: "us-west-2",
endpoint: "http://localhost:8000"
});
var docClient = new AWS.DynamoDB.DocumentClient()
var table = "Movies";
var year = 2015;
var title = "The Big New Movie";
// Update the item, unconditionally,
// Key is super important to tell AWS to identify an item.
var params = {
TableName:table,
Key:{
"year": year,
"title": title
},
UpdateExpression: "set info.rating = :r, info.plot=:p, info.actors=:a",
ExpressionAttributeValues:{
":r":5.5,
":p":"Everything happens all at once.",
":a":["Larry", "Moe", "Curly"]
},
ReturnValues:"UPDATED_NEW"
};
console.log("Updating the item...");
docClient.update(params, function(err, data) {
if (err) {
console.error("Unable to update item. Error JSON:", JSON.stringify(err, null, 2));
} else {
console.log("UpdateItem succeeded:", JSON.stringify(data, null, 2));
}
});
Run node WHATEVER_YOUR_NAME_OF_THE_FILE
Tada! the item from table MOVIE is now updated
Question: How would we update multiple items in AWS using this info? Can we run a loop?
Top comments (0)