Node.js 使用Lambda将项添加到DynamoDB中映射嵌套的数组中
我试图将一个项目添加到一个列表中,该列表嵌套在DynamoDB中的另一个对象列表中。我正在传递Node.js 使用Lambda将项添加到DynamoDB中映射嵌套的数组中,node.js,amazon-web-services,aws-lambda,amazon-dynamodb,Node.js,Amazon Web Services,Aws Lambda,Amazon Dynamodb,我试图将一个项目添加到一个列表中,该列表嵌套在DynamoDB中的另一个对象列表中。我正在传递“userid”:“041c9004”和“author”:“J.K Rowling”。我想将字符串“hermoine”添加到图书列表第二项中的字符列表中。函数首先在图书列表中查找“J.K Rowling”对象的索引。然后,它应该使用该索引将字符串插入到正确的字符列表中。但是,此代码引发了一个错误 DynamoDB表看起来像这样。userid是主键: { "books": [
“userid”:“041c9004”
和“author”:“J.K Rowling”
。我想将字符串“hermoine”添加到图书
列表第二项中的字符
列表中。函数首先在图书列表中查找“J.K 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);
}
});
}
}
});