Reputation: 2741
In the request, I may or may not have an "email" field.
In my DynamoDB update call I want to construct an UpdateExpression such that it will update the "email" field based on the value of the request, but if not found then use the previous value of the field.
It updates properly when I put "email" in the request, but if I don't, it just updates the field to the literal string, userProfile.email, instead of the path, userProfile.email
controller.js:
async function updateUserProfile(ctx) {
if (ctx.params && ctx.params.userId) {
try {
const data = await db('update')({
TableName: TABLE_NAMES.USERS,
Key: {
userId: ctx.params.userId,
},
ExpressionAttributeValues: {
':email': ctx.request.body.email || 'userProfile.email' || null,
},
UpdateExpression:
'set userProfile.email = :email,
});
ctx.status = 200;
ctx.body = data;
} catch (error) {
ctx.throw(400, error);
}
}
}
If my request body looks like this:
{ "email": "newEmail" }
then the updated User Item will look like something like this:
{ "userProfile": { "email": "newEmail" }
which is intended, but if I don't include "email" in the request body, the updated User Item looks like this:
{ "userProfile": { "email": "userProfile.email" }
It seems the UpdateExpression is taking the string literally instead of converting it to a path. I probably could use a ConditionExpression, but there are other fields than "email" and they too would require their own ConditionExpression, and I can only have one in a call.
How do I make it see the value as a path, or is there another way I can update with the previous attribute value?
Upvotes: 0
Views: 1192
Reputation: 304
Its problem with the way you are setting the value for EMAIL
ExpressionAttributeValues: {
':email': ctx.request.body.email || 'userProfile.email' || null,
}
when you dont have value for ctx.request.body.email, then email is set to 'userProfile.email'. For you code to work, you should first check if ctx.request.body.email!=null, then only assign the email value. In other words, you need to first construct the expressionattributes dynamically and the set that variable.
ExpressionAttributeValues: { 'expressionattributevaluevriable' }
Upvotes: 1