简体   繁体   English

Dynamodb - 更新对象数组中JSON对象的值

[英]Dynamodb - Update value of JSON object in array of objects

Below is a sample item object/record stored in DynamoDb. 下面是存储在DynamoDb中的示例项目对象/记录。 I use NodeJS and AWS.DynamoDB.DocumentClient to access the database. 我使用AWS.DynamoDB.DocumentClientAWS.DynamoDB.DocumentClient来访问数据库。

I'm building out a PUT function to update the status for an JSON object in an array. 我正在构建一个PUT函数来更新数组中JSON对象的状态。 The function will have access to the Item's uuid and room's uuid . 该函数可以访问Item的uuid和room的uuid How can I simply (creatively) update the value of corresponding status field, given the array of JSON objects? 在给定JSON对象数组的status ,如何(创造性地)更新相应status字段的值?

Params: PARAMS:

let params = {
  TableName: room-table,
  Key: {
    uuid: event.body.uuid
  },
  UpdateExpression : "??",
  ExpressionAttributeNames: {
      "??":"??"
  },
  ExpressionAttributeValues:{
    "??":"??"
  },
  ReturnValues:"ALL_NEW"
};

Item Object: 物品对象:

{
  "Item": {
    "uuid": "77b1e88e-5e60-44d9-b6ca-aec345c0dc99",
    "rooms": [
      {
        "room": "303",
        "status": "pending",
        "uuid": "b8f1c1a8-04a9-4c2e-82ad-bc3e81face35"
      },
      {
        "room": "302",
        "status": "pending",
        "uuid": "42fdc61a-4a25-4316-90c9-60209875d208"
      },
      {
        "room": "678",
        "status": "pending",
        "uuid": "7bedc115-20ed-4c3e-9cd7-7fed0520f4df"
      }
    ],
    "status": "pending"
  }
}

It's not possible to do this with ExpressionAttributeValues . 使用ExpressionAttributeValues无法做到这一点。 I had to build a function to modify the object, similar to below: 我必须构建一个修改对象的函数,类似于下面:

function setStatus(jsonObj, uuid, newStatus) {
  for (var i=0; i<jsonObj.length; i++) {
    if (jsonObj[i].uuid === uuid) {
      jsonObj[i].status = newStatus;
      return jsonObj;
    }
  }
}
let params = {
  TableName: room-table,
  Key: {
    uuid: event.body.uuid
  },
  UpdateExpression : "SET #stat = :stat",
  ExpressionAttributeNames: {
      "#stat": "status"
  },
  ExpressionAttributeValues:{
    ":stat": "updatedStatusValue"
  },
  ReturnValues:"ALL_NEW"
};

ExpressionAttributeNames is needed because status is a DynamoDB reserved word . 需要ExpressionAttributeNames,因为status是DynamoDB保留字 More info on Attribute Name and Attribute Value placeholders is available in the DynamoDB docs . 有关属性名称和属性值占位符的更多信息,请参见DynamoDB文档

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

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