Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

524
Views
Increment the value if it exists, else add a new entry in DynamoDB

I have a DynamoDB table with columns and primary key as ipAddress:

  • ipAddress
  • visits

I am fetching the IP address of the user from my react website and inserting it to DynamoDB via a Lambda function and API Gateway POST request.

If the IP address coming from the React website is already present in the DynamoDB, then increment the value in visits column. If not, then create a new record with the new IP address and visits = 1. I tried using ConditionExpression but to no avail.

So far, I am only inserting the ipAddress using Lambda. Below is my Lambda function in NodeJS:

const AWS = require("aws-sdk");
const documentClient = new AWS.DynamoDB.DocumentClient();

exports.handler = async event => {
  const { ipAddress} = JSON.parse(event.body);
  const params = {
    TableName: "ipAddress",
    Item: {
      ipAddress: ipAddress,
    }
  };

  try {
    const data = await documentClient.put(params).promise();
    const response = {
      statusCode: 200,
    };
    return response;
  }
  catch (e) {
    return {
      statusCode: 500,
      body: JSON.stringify(e)
    };
  }

};
over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

We need to use update-item rather than put-item, both creates a record if record doesn't exist. But update-item accepts UpdateExpression to help us update an existing attribute.

UpdateExpression: "SET visits = if_not_exists(visits, :initial) + :num"

if_not_exists helps to use initial value for the first time when attributes visits doesn't exist.

docClient.update(
  {
    TableName: "ipAddress",
    Key: {
      ipAddress: ipAddress,
    },
    UpdateExpression: "SET visits = if_not_exists(visits, :initial) + :num",
    ExpressionAttributeValues: {
      ":num": 1,
      ":initial": 0,
    },
  },
  function (error, result) {
    console.log("error", error, "result", result);
  }
);
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!