0
votes

Hi I am newbie to dynamoDB. Below is the schema of the dynamo table

{
   "user_id":1, // partition key
   "dob":"1991-09-12", // sort key 
   "movies_watched":{
      "1":{
         "movie_name":"twilight",
         "movie_released_year":"1990",
         "movie_genre":"action"
      },
      "2":{
         "movie_name":"harry potter",
         "movie_released_year":"1996",
         "movie_genre":"action"
      },
      "3":{
         "movie_name":"lalaland",
         "movie_released_year":"1998",
         "movie_genre":"action"
      },
      "4":{
         "movie_name":"serendipity",
         "movie_released_year":"1999",
         "movie_genre":"action"
      }
   }
..... 6 more attributes

}

I want to insert a new item if the item(that user id with dob) did not exist, otherwise add the movies to existing movies_watched map by checking if the movie is not already available the movies_watched map .

Currently, I am trying to use update(params) method.

Below is my approach:

function getInsertQuery (item) {
  const exp = {
    UpdateExpression: 'set',
    ExpressionAttributeNames: {},
    ExpressionAttributeValues: {}
  }
  Object.entries(item).forEach(([key, item]) => {
    if (key !== 'user_id' && key !== 'dob' && key !== 'movies_watched') {
      exp.UpdateExpression += ` #${key} = :${key},`
      exp.ExpressionAttributeNames[`#${key}`] = key
      exp.ExpressionAttributeValues[`:${key}`] = item
    }
  })

  let i = 0
  Object.entries(item. movies_watched).forEach(([key, item]) => {
    exp.UpdateExpression += ` movies_watched.#uniqueID${i} = :uniqueID${i},`
    exp.ExpressionAttributeNames[`#uniqueID${i}`] = key
    exp.ExpressionAttributeValues[`:uniqueID${i}`] = item
    i++
  })
  exp.UpdateExpression = exp.UpdateExpression.slice(0, -1)
  return exp
}

The above method just creates update expression with expression names and values for all top level attributes as well as nested attributes (with document path).

It works well if the item is already available by updating movies_watched map. But throws exception if the item is not available and while inserting. Below is exception:

The document path provided in the update expression is invalid for update

However, I am still not sure how to check for duplicate movies in movies_watched map

Could someone guide me in right direction, any help is highly appreciated!

Thanks in advance