使用NodeJS将新对象附加到DynamoDB中的JSON数组

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (1)
  • 关注 (0)
  • 查看 (54)

我使用JSON结构来存储一个人的细节。基本上名称,电话,registeredTimestamp等,将是其他属性,主键将是电子邮件地址。

AWS在调用它时,标记位置,visitedLocations,searchHistory和推荐是列表或Map。它将包含许多JSON对象。

JSON结构:

{
    "name":"Mama Miya",
    "phone":"9383883223",
    "registeredTimestamp":"some-time",
    "lastActiveTimestamp":"some-time",
    "signinType":"facebook",
    "additionalSigninData":{
        "key1":"value1",
        "key2":"value2"
    },
    "markedLocations":[
        {
            "latitude":"77.33",
            "longitude":"12.33",
            "name":"Home",
            "description":"my new home",
            "placeid":"55334433",
            "image":"url/abc.png"
        }
    ]
}

从应用程序中,如果用户访问新位置,则需要将新的JSON对象添加到markedLocations。所以标记的位置应该看起来像 -

"markedLocations":[
    {
        "latitude":"77.33",
        "longitude":"12.33",
        "name":"Home",
        "description":"my new home",
        "placeid":"55334433",
        "image":"url/abc.png"
    },{
        "latitude":"22.11",
        "longitude":"22.55",
        "name":"Ocean",
        "description":"Ocean",
        "placeid":"32423423",
        "image":"url/icean.png"
    }
]

代码/时间表

var item = {
        'email': {'S': req.body.email},
        'phone': {'S': req.body.phone},
        'registeredTimestamp': {'S': req.body.registeredTimestamp},
        'lastActiveTimestamp': {'S': req.body.lastActiveTimestamp},
        'signinType': {'S': req.body.signinType},
        'version': {'S': req.body.version},
        'markedLocations': {'L': req.body.markedLocations}
    };

是否有方法在NodeJS中添加一个新的JSON对象的JSON数组?

我应该为每个数组创建单独的表并将电子邮件作为主键和时间戳作为排序键并继续?

提问于
用户回答回答于
var AWS = require('aws-sdk')
var DB = new AWS.DynamoDB.DocumentClient()

function appendMarkedLocation (personId, location) {
  return DB.update({
    TableName: 'people',
    Key: { id: personId },
    ReturnValues: 'ALL_NEW',
    UpdateExpression: 'set #markedLocations = list_append(if_not_exists(#markedLocations, :empty_list), :location)',
    ExpressionAttributeNames: {
      '#markedLocations': 'markedLocations'
    },
    ExpressionAttributeValues: {
      ':location': [location],
      ':empty_list': []
    }
  }).promise()
}

appendMarkedLocation('somePeronId', {
  latitude: '22.11',
  longitude: '22.55',
  name: 'Ocean',
  description: 'Ocean',
  placeid: '32423423',
  image: 'url/icean.png'
}).then(console.log)

扫码关注云+社区

领取腾讯云代金券