问题描述
我正在创建一个使用 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 尝试添加到集合 - 操作数不正确的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!