Tob*_*obi 19 amazon-web-services node.js amazon-dynamodb
我只想将 id + 一些值添加到 DynamoDb 一次。如果 id 已经存在,它应该什么都不做或更新
我可以去
search
if not found > insert
if found > do nothing or update (for now do nothing is fine)
Run Code Online (Sandbox Code Playgroud)
但希望有更好的方法来做到这一点。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);
});
Run Code Online (Sandbox Code Playgroud)
我在 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}
Run Code Online (Sandbox Code Playgroud)
Mil*_*mak 45
您可以使用单个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);
}
}
Run Code Online (Sandbox Code Playgroud)
如果您只想在不存在的情况下插入,您可以使用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);
}
}
Run Code Online (Sandbox Code Playgroud)
通过组合条件表达式和更新表达式,您可以想出更复杂的方法来设置或更新项目中的属性。
注意我还没有完全测试代码,所以如果有任何错误,请发表评论,但它应该可以工作。
| 归档时间: |
|
| 查看次数: |
31433 次 |
| 最近记录: |