尝试添加到集合的AWS DynamoDB-错误的操作数 [英] AWS DynamoDB Attempting to ADD to a Set - Incorrect Operand
问题描述
我正在使用Nodejs和DynamoDB作为后端创建一个API。我试图更新一个项目以添加到一组朋友中。更新用户时,出现错误无效的UpdateExpression:运算符或函数的操作数类型不正确;运算符:ADD,操作数类型:MAP。我的理解是,当添加到不存在的集合时,将创建该集合。如果已经存在,则应将新值添加到集合中。我不明白为什么我尝试添加的集合被作为地图读取。
I am creating an API using Nodejs and DynamoDB as a back end. I am attempting to update an item to add to a set of "friends". When I update the user, I get the error, "Invalid UpdateExpression: Incorrect operand type for operator or function; operator: ADD, operand type: MAP". My understanding is that when adding to a set that does not exist, the set will be created. If it already exists, the new value should be added to the set. I do not understand why the set I attempt to ADD is being read as a map.
如何创建用户:
var params = {
TableName: "users",
Item:{
"id": Number(id),
"name": name,
"password": password
}
};
documentClient.put(params, function(err, data) {
if(err)
res.json(500, err);
else
res.json(200, data);
});
如何添加朋友:
var params = {
TableName: "users",
Key: {
"id": id
},
UpdateExpression: "ADD friends :friendId",
ExpressionAttributeValues: {
":friendId": { "NS": [friendId] }
},
ReturnValues: "UPDATED_NEW"
};
documentClient.update(params, function(err, data) {
if(err)
res.json(500, err);
else
res.json(200, data);
});
推荐答案
问题在这里有答案
https://stackoverflow.com/a/38960676/4975772
以下是格式化为适合您问题的相关代码
Here's the relevant code formatted to fit your question
let AWS = require('aws-sdk');
let docClient = new AWS.DynamoDB.DocumentClient();
...
var params = {
TableName : 'users',
Key: {'id': id},
UpdateExpression : 'ADD #friends :friendId',
ExpressionAttributeNames : {
'#friends' : 'friends'
},
ExpressionAttributeValues : {
':friendId' : docClient.createSet([friendId])
},
ReturnValues: 'UPDATED_NEW'
};
docClient.update(params, callback);
如果该集合不存在,那么该代码将为您创建。您还可以使用其他集合运行该代码以更新集合的元素。超级方便。
If the set doesn't exist, then that code will create it for you. You can also run that code with a different set to update the set's elements. Super convenient.
这篇关于尝试添加到集合的AWS DynamoDB-错误的操作数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!