DynamoDB if attribute doesn't exist create it, in node.js

Viewed 414

I'm trying to update a user objects attribute which may not exist.

The attribute is called claimed which itself will have a property for each currency type #c1 (USD, euro, ect). A user can have multiple currencies but starts with none so claimed may or may not exist on a user object.

My initial draft was:

let params = {
  TableName: 'myproject-user',
  Key: {"id":req.user.sub},
  UpdateExpression: 'set claimed.#c1 = :o',
  ExpressionAttributeValues:{
    ":o": req.body.currency
  },
  ExpressionAttributeNames:{ "#c1": req.body.currency.type },
  ReturnValues:"UPDATED_NEW"
};

This returns the error:

"Error: ValidationException: The document path provided in the update expression is invalid for update"

I've tried some variations using if_not_exists but I can't seem to get it working. How can I modify the params to have the desired effect?

1 Answers

you can use ConditionExpression: "attribute_not_exists(<YOUR_ATTRIBUTE>)"

for example:

let params = {
  TableName: 'myproject-user',
  Key: {"id":req.user.sub},
  UpdateExpression: 'set claimed.#c1 = :o',
  ExpressionAttributeValues:{
    ":o": req.body.currency
  },
  ExpressionAttributeNames:{ "#c1": req.body.currency.type },
  ConditionExpression: "attribute_not_exists(claimed.#c1)",
  ReturnValues:"UPDATED_NEW"
};
Related