我只想向DynamoDb添加一次id +一些值。如果该ID已经存在,则不应执行任何操作或进行更新
我可以一起去
search
if not found > insert
if found > do nothing or update (for now do nothing is fine)
但是希望有更好的方法可以做到这一点。 id应该是检查的关键。
那是节点中的代码:
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中进行设置的选项
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}
最佳答案
您可以通过一个UpdateItem操作来完成整个操作:
const dynamodbParams = {
TableName: process.env.DYNAMODB_TABLE_BLICKANALYTICS,
Key: {id: userId},
UpdateExpression: 'SET createdAt = if_not_exists(createdAt, :ca)',
ExpressionAttributeValues: {
':ca': {'S': timestamp}
}
};
dynamoDb.updateItem(params, function(err, data) {
if (err) {
console.log(err, err.stack);
} else {
console.log(data);
}
}
如果只想在不存在的情况下进行插入,则可以使用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);
}
}
您可以通过结合condition expressions和update expressions提出更复杂的方法来设置或更新项目中的属性。
注意:我尚未完全测试代码,因此请注释是否有任何错误,但它应该可以工作。
关于node.js - 即使 key 不存在,如何插入DynamoDb,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55106784/