dynamiodb在列表nodejs内的对象内的列表中添加对象

时间:2018-02-21 18:03:55

标签: javascript node.js amazon-web-services aws-lambda amazon-dynamodb

我在DynamoDB中使用过这种类型的对象,我想为它添加一个设备。

     {
        "user": "user2",
        "pass": "pass2",
        "name": "persona1",
        "lastname": "person2",
        "places":
        [
        {
          "name": "bedroom",
          "devices": [{
                      "name": "Lampara",
                      "chip": "esp8266_D98FF1"
                    },
                    {
                      "name": "Puerta",
                      "chip": "esp8266_1F852F"
                    }]
        }
      ]
  }

我想在卧室添加一个新设备,如

{
     "name": "bed",
      "chip": "esp8266_44444F"
}

如何将一个对象添加到Dynamodb中,如果它嵌套了?

编辑:我解决了搜索区域索引并发出此请求的问题。

for (var i = 0; i < req.session.Item.zonas.length; i++) {
  if (req.session.Item.zonas.nombre == req.body.zona){
    index = i;
  }
}
var devicetoAdd = {
     "nombre": req.body.nombre,
     "chip": req.body.cod
};
var params = {
    TableName: "usuarios",
    Key:{
        "user": req.session.user
    },
    UpdateExpression: "set zonas[" + index+ "].devices = list_append(zonas[" + index+ "].devices, :vals)",
    ExpressionAttributeValues: {
      ":vals": [devicetoAdd]
    },
    ReturnValues:"UPDATED_NEW"
};

1 个答案:

答案 0 :(得分:1)

假设该对象可以包含多个具有相同名称的位置,则可以使用函数forEach

var obj = {  TableName: "usuarios",  Item: {    "user": "user2",    "pass": "pass2",    "name": "persona1",    "lastname": "person2",    "places": [{      "name": "bedroom",      "devices": [{          "name": "Lampara",          "chip": "esp8266_D98FF1"        },        {          "name": "Puerta",          "chip": "esp8266_1F852F"        }      ]    }]  }};

obj.Item.places.forEach(p => {
  if (p.name === 'bedroom') {
    p.devices.push({ "name": "bed", "chip": "esp8266_44444F" })
  }
});

console.log(obj)
.as-console-wrapper { max-height: 100% !important; top: 0; }