Jak aktualizovat položku v tabulce dynamoDB

Upozornění:Toto není můj původní nápad. Podívejte se prosím na tento odkaz pro segment dokumentace AWS, který zde chci představit.

Jak aktualizuji položku v tabulce dynamoDB?

Nejprve se můžete přímo přihlásit k AWS a aktualizovat položku. V tomto příspěvku na blogu provedeme tento úkol z kódu vizuálního studia (nebo jakéhokoli editoru, který používáte) a uzlu .

Řekněme například, že bychom chtěli aktualizovat položku filmu z:

{
   year: 2015,
   title: "The Big New Movie",
   info: {
        plot: "Nothing happens at all.",
        rating: 0
   }
}

na:

{
   year: 2015,
   title: "The Big New Movie",
   info: {
           plot: "Everything happens all at once.",
           rating: 5.5,
           actors: ["Larry", "Moe", "Curly"]
   }
}

K tomu musíme nejprve najít položku z databáze AWS (dynamoDB) a sdělit této službě, že se jedná o položku, kterou aktualizujeme. Podívejme se, jak toho AWS-SDK* dosahuje.


/**
 * 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));
    }
});

Spusťte node WHATEVER_YOUR_NAME_OF_THE_FILE

Tada! položku z tabulky FILM je nyní aktualizován