我正在尝试从AWS Lambda设置一个小api到DynamoDB,我无法弄清楚是否以及如何将对象数组写入密钥。
我有像
这样的对象{
"teamName": "Team Awesome",
"members": [
{
"email": "person-1@example.com",
"name": "Bob"
},
{
"email": "person-2@example.com",
"name": "Alice"
}
]
}
成员数组给了我一些问题,在文档中它看起来可以考虑列表类型来完成,但是没有例子如何做到这一点,并且我没有办法尝试它。
所以可以用这种格式写一些东西,在这种情况下你怎么做呢?
示例代码 - 我将什么内容放在???
var AWS = require('aws-sdk');
var dynamodb = new AWS.DynamoDB();
exports.handler = function(event, context) {
var tableName = "GDCCompetition";
var datetime = new Date().getTime().toString();
DynamoDB.putItem({
"TableName": tableName,
"Item": {
"datetime": {
"N": datetime
},
"teamName": {
"S": event.teamName
},
"members": ???
}
});
}
答案 0 :(得分:26)
文档并不是很明显,但是有一个名为DocClient
的东西,你可以将一个普通的JS对象传递给它,它将完成所有解析和转换到AWS对象(包含所有类型)。您可以像这样使用它:
var AWS = require("aws-sdk");
var DynamoDB = new AWS.DynamoDB.DocumentClient();
var params = {
TableName: "MyTable",
Item: {
"teamName": "Team Awesome",
"members": [
{
"email": "person-1@example.com",
"name": "Bob"
},
{
"email": "person-2@example.com",
"name": "Alice"
}
]
}
};
DynamoDB.put(params, function (err) {
if (err) {
return throw err;
}
//this is put
});
答案 1 :(得分:2)
您可以先将对象转换为DynamoDb记录
const AWS = require('aws-sdk');
var tableName = "GDCCompetition";
var datetime = new Date().getTime().toString();
const members = [
{
"email": "person-1@example.com",
"name": "Bob"
},
{
"email": "person-2@example.com",
"name": "Alice"
}
];
const marshalled = AWS.DynamoDB.Converter.marshall({ members });
const params = {
"TableName": tableName,
"Item": {
"datetime": {
"N": datetime
},
"teamName": {
"S": event.teamName
},
"members": marshalled.members,
},
}
AWS.DynamoDB.putItem(params, function (err) {
if (err) {
return throw err;
}
});