Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

525
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda