Tushar Gaurav
Tushar Gaurav

Reputation: 506

Serverless: dynamodb giving error on create record when trying with async/await

I am trying to create a record in dynamodb(Using dynamoose). code is

class Test {
  constructor() {
    this.table = dynamoose.model(tableName, tableSchema);
  }
//  userdata object - { 
//  cusotmerEmail: '[email protected]',
//  customerBusinessName: 'DoogleDnd',
//  customerFirstName: 'Tushar',
//  customerId: 101211,
//  customerLastName: 'Gaurav',
//  isDeleted: false,
//  sku: '100',
//  userId: '5c1776e94bea867c3f896236' 
// }


  async createUser(userData) {
    try {
      const res = await this.table.create(userData);
      console.log('Update user record - ', res);
      return res;
    } catch (error) {
      throw new Error(error);
    }
  }
}

*input values to the create function are correct as the same input I tried with batchPut(), it's working. And even update call to the table is also working.

async updateUser(userData) {
    try {
      const res = await this.table.update(userData);
      console.log('Updated user record - ', res);
      return res;
    } catch (error) {
      throw new Error(error);
    }
 }

This is the error I am getting - Error - {"message":"The conditional request failed", "code":"ConditionalCheckFailedException", "statusCode":400}

This is the calling function -

module.exports.subscribeUser = async (event) => {
  let inputBody = (typeof event.body === 'object' ? event.body : 
  JSON.parse(event.body));
  inputBody.userId = event.pathParameters.id;
  try {
    // Validate input
    await asisvc.validateInput(inputBody);

    inputBody = await UserSvc.constructUserObject(inputBody);
    console.log('Constructed object - ', JSON.stringify(inputBody));

    const userData = await testObj.createUser(inputBody);
    return Utils.buildResp(codes.ok, { userData }, {});
  } catch (error) {
    console.log(error);
    return Utils.buildResp(codes.badrequest, { Error: 
Utils.getErrString(error) }, {});

} };

I tried googling it, but didn't find any proper document. Thanks in advance.

Upvotes: 0

Views: 759

Answers (1)

Charlie Fish
Charlie Fish

Reputation: 20526

In Dynamoose by default we check to see if the primary key already exists in the table when using the Model.create method.

So your error:

{"message":"The conditional request failed", "code":"ConditionalCheckFailedException", "statusCode":400}

Indicates that the primary key already exists in the table. So you are trying to create a duplicate item.

In the documentation there is an options property that you can use to allow overriding the object.

For example the following code will allow overrides:

const res = await this.table.create(userData, {overwrite: true});

Upvotes: 1

Related Questions