简体   繁体   English

如何使用 javascript 对象部分更新 DynamoDB 中的项目?

[英]How to partially update an item in DynamoDB with a javascript object?

I have items in a DynamoDB database table and I want to update an existing item but only a few attributes of it instead of everything.我在 DynamoDB 数据库表中有项目,我想更新现有项目但只更新它的几个属性而不是所有属性。 I know I can do that with for example AWS.DynamoDB.DocumentClient, using the update() function and passing UpdateExpression with the attributes I want to update in the params.我知道我可以使用 AWS.DynamoDB.DocumentClient 来做到这一点,使用 update() 函数并将 UpdateExpression 与我想在参数中更新的属性一起传递。 I also know that I can loop through the properties of the javascript object and construct an update expression based on that but I suspect there must be an easier way to do this.我也知道我可以遍历 javascript 对象的属性并基于它构造一个更新表达式,但我怀疑必须有更简单的方法来执行此操作。

So instead of something like this (and having to implement the two fetch* functions):所以不要像这样(并且必须实现两个 fetch* 函数):

const ddbDocClient = new AWS.DynamoDB.DocumentClient();
const params = {
  TableName: 'SomeTable',
  Key: { id: someId },
  UpdateExpression: fetchPropertiesOfAJavascriptObjectAndMakeAnExpressionStringOfThem(obj),
  ExpressionAttributeValues: fetchValuesOfAJavascriptObjectAndMakeAValuesStringOfThem(obj)
}
ddbDocClient.update(params, (err, data) => {/* do something */});

I would like to do something like我想做类似的事情

const ddbDocClient = new AWS.DynamoDB.DocumentClient();
const params = {
  TableName: 'SomeTable',
  Key: { id: someId },
  AttributesToUpdate: obj
}
ddbDocClient.update(params, (err, data) => {/* do something */});

You cannot do so directly using the low level API, as you need to set the UpdateExpression .您不能直接使用低级 API 这样做,因为您需要设置UpdateExpression

You would need to use an object mapper type client which is not directly available via the SDK but can be obtained here:您需要使用对象映射器类型的客户端,该客户端无法通过 SDK 直接获得,但可以在此处获取:

https://github.com/awslabs/dynamodb-data-mapper-js https://github.com/awslabs/dynamodb-data-mapper-js

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM