繁体   English   中英

使用适用于 Node.js 的 AWS 开发工具包将项目放在 DynamoDB 表上

[英]Put item on DynamoDB table using AWS SDK for Node.js

我是 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
    }
});
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 .................."); 

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

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

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

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

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

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

我建议使用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) } });

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM