[英]Add item to array nested within a map in DynamoDB using Lambda
我正在尝试将一个项目添加到嵌套在 DynamoDB 中另一个对象列表中的列表中。 我正在传递"userid" : "041c9004"
和"author": "JK Rowling"
。 我想将字符串“hermoine”添加到books
列表第二项中的characters
列表中。 该函数首先在书籍列表中查找“JK Rowling”对象的索引。 然后,它应该使用该索引将字符串插入到正确的字符列表中。 但是,此代码引发错误。
DynamoDB 表如下所示。 userid 是主键:
{
"books": [
{
"author": "J.R.R. Tolkien",
"characters": ["frodo","sam","bilbo"],
"title": "Lord of the Rings"
},
{
"author": "J.K Rowling",
"characters": ["harry","ron"],
"title": "Harry Potter"
}
],
"lastupdated": 1597690265,
"userid": "041c9004"
}
这是 Lambda 函数:
const AWS = require('aws-sdk');
const docClient = new AWS.DynamoDB.DocumentClient({region: 'us-east-1'});
exports.handler = function(event, context, callback){
var params = {
TableName: 'Users',
Key: {
userid: event.userid
}
};
docClient.get(params, function(err, data){
if(err) {
callback(err,null);
} else {
var indexOfAuthor = data.Item.books.findIndex(i => i.author === event.author);
console.log('The index of the author is ' + indexOfAuthor);
if (indexOfAuthor == -1) {
callback(err, null);
} else {
let paramsadd = {
ExpressionAttributeValues: {
":character": ["hermoine"]
},
ExpressionAttributeNames : {
// this is likely where the issue is
"#attrName" : "books[" + indexOfAuthor + "].characters"
},
Key: {
userid: event.userid
},
TableName: 'Users',
UpdateExpression: "SET #attrName = list_append(#attrName, :character)",
ReturnValues:"ALL_NEW",
};
docClient.update(paramsadd, function(err,data){
if(err) {
callback(err, null);
}else{
callback(null, data);
}
});
}
}
});
};
这是抛出的错误:
ERROR Invoke Error {"errorType":"ValidationException","errorMessage":"The provided expression refers to an attribute that does not exist in the item","code":"ValidationException","message":"The provided expression refers to an attribute that does not exist in the item"
这是解决方案:
docClient.get(params, function(err, data){
if(err) {
callback(err,null);
} else {
var indexOfAuthor = data.Item.books.findIndex(i => i.author === event.author).toString();
console.log('The index of the author is ' + indexOfAuthor);
var attrnamval = `books[${indexOfAuthor}].characters` ;
if (indexOfAuthor == -1) {
callback(err, null);
} else {
let paramsadd = {
ExpressionAttributeValues: {
":character": ["hermoine"]
},
Key: {
userid: event.userid
},
TableName: 'Users',
UpdateExpression: `SET ${attrnamval} = list_append(${attrnamval}, :character)`,
ReturnValues:"ALL_NEW",
};
docClient.update(paramsadd, function(err,data){
if(err) {
callback(err, null);
}else{
callback(null, data);
}
});
}
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.