使用适用于Node.js的AWS SDK将项目放到DynamoDB表中

htrmnn0y  于 2022-11-04  发布在  Node.js
关注(0)|答案(5)|浏览(153)

我是javascript和node.js的新手,想知道是否有人能帮助我通过node.js SDK弄清楚将新项目放到AWS Dynamodb上的现有表中的语法。下面是我目前所掌握的。有没有我正在尝试做的示例?如果有人能给我指出正确的方向,我将非常感激。

var AWS = require('aws-sdk');
AWS.config.loadFromPath('./config.json');
AWS.config.update({region: 'us-east-1'});
var dynamodb = new AWS.DynamoDB();

var item = {
    // I need to put the an item with a the primary key of "id", and an attribute called "item"
    // I'm new to js and node.js, so if somebody could help me understand the documentation
    // http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/frames.html#!http%3A//docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB_20120810.html
}

dynamodb.putItem({TableName: 'log_dev', Item: item}, function(err, data){
    if (err) {
    console.log(err); // an error occurred
    } else {
    console.log(data); // successful response
    }
});
30byixjq

30byixjq1#

dynamoDB.putItem(
{
    "TableName": "Table1",
    "Item": {
        "Color": {"S": "white"},
        "Name": {"S": "fancy vase"},
        "Weight": {"N": "2"},
        "LastName":{"S": "Kumar"}
    }
}, function(result) {
    result.on('data', function(chunk) {
        console.log("" + chunk);
    });
});
console.log("Items are succesfully ingested in table ..................");
3gtaxfhh

3gtaxfhh2#

我希望你的“id”是数字...

var item = {
    "id": {"N": 1234},
    "title": {"S": "Foobar"}
}

注意,使用DynamoDB,您在创建表时指定数据类型(N numeric,S string,B binary),仅用于主键(HashKeyHashKey+RangeKey)。所有其他列的数据类型都允许变化,并且可以被视为键-值对。因此,DynamoDB必须始终使用项属性对数据类型进行编码。

ykejflvf

ykejflvf3#

我不认为muhqu的答案有效,我认为属性的值必须是字符串。

var item = {
"id": {"N": "1234"},
"title": {"S": "Foobar"} }

http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB.html#putItem-property

64jmpszr

64jmpszr4#

我建议使用documentClient,因为它使在dynamoDb中读取和写入数据更容易。同时使用条件putItem将确保项是唯一的,并且不会覆盖现有项。“attribute_not_exists”检查示例中的userId是否不存在。如果userId存在,它将抛出错误。希望现在还不算太晚:P

var AWS = require('aws-sdk');
AWS.config.loadFromPath('./config.json');
AWS.config.update({region: 'us-east-1'});
var dynamodb = new AWS.DynamoDB.DocumentClient();

var item = {
"userId" : {"N":"12345678"},
"name":{"S":"Bob"}
}

var dbParam= {
TableName: tableName,
Item:item,
ConditionExpression: 'attribute_not_exists(#u) or #u = :userId',
ExpressionAttributeNames: { "#u" : "userId"}
}

dynamodb.putItem(dbParam, function(err,data) {
if(err){
console.log("err",err);
}
else{
console.log("data",data)
}
});
m528fe3b

m528fe3b5#

使用aws-sdk时,您可以使用类似以下的内容:

import { DynamoDB } from 'aws-sdk';

const dynamo = new DynamoDB.DocumentClient();

const main = async () => {
    const results = await dynamo
        .put({
            TableName: 'people',
            Item: {
              dateCreated: { S: new Date().toUTCString() },
              name: { S: name },
            },
        })
        .promise();

    console.log(JSON.stringify(results));
};

main();

相关问题