即使密钥不存在,如何插入DynamoDb [英] How to insert to DynamoDb just if the key does not exist

查看:93
本文介绍了即使密钥不存在,如何插入DynamoDb的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只想向DynamoDb添加一次id +一些值.如果该ID已经存在,则不应执行任何操作或更新

I want to add id + some values to a DynamoDb just once. If the id exists already it should do nothing or update

我可以和

search 

if not found > insert

if found > do nothing or update (for now do nothing is fine)

但希望有更好的方法来做到这一点.ID应该是检查的关键.

But hopfully there is a better way to do it. The id should be the key to check for.

那是节点中的代码:

const dynamodbParams = {
        TableName: process.env.DYNAMODB_TABLE_BLICKANALYTICS,
        Item: {
          id: userId,
          createdAt: timestamp
        },
      };

      dynamoDb.put(dynamodbParams).promise()
      .then(data => {
        console.log('saved: ', dynamodbParams);
      })
      .catch(err => {
        console.error(err);
      });  

我在yml中使用它.不知道是否有在yml中设置的选项

I use this in yml. Don't know if there are options to set this up in yml

resources:
  Resources:
    DynamoDbTableExpenses:
      Type: 'AWS::DynamoDB::Table'
      DeletionPolicy: Retain
      Properties:
        AttributeDefinitions:
          -
            AttributeName: id
            AttributeType: S
          -  
            AttributeName: createdAt
            AttributeType: N
        KeySchema:
          -
            AttributeName: id
            KeyType: HASH
          -
            AttributeName: createdAt
            KeyType: RANGE            
        ProvisionedThroughput:
          ReadCapacityUnits: 1
          WriteCapacityUnits: 1
        TableName: ${self:provider.environment.DYNAMODB_TABLE_BLICKANALYTICS}

推荐答案

您可以使用一个如果只想插入(如果不存在),则可以使用

If you only want to do insert if not exists, you can easily do that with PutItem:

const dynamodbParams = {
    TableName: process.env.DYNAMODB_TABLE_BLICKANALYTICS,
    Item: {
        id: userId,
        createdAt: timestamp
    },
    ConditionExpression: 'attribute_not_exists(id)'
};
dynamodb.putItem(params, function(err, data) {
    if (err) {
        console.log(err, err.stack);
    } else {
        console.log(data);
    }
}

通过结合更新表达式.

请注意,我尚未完全测试代码,因此请注释是否有任何错误,但应该可以.

Note I have not fully tested the code, so please comment if there's any error, but it should work.

这篇关于即使密钥不存在,如何插入DynamoDb的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆