任何人都可以提供动态文档客户端upsert的示例吗?

rob*_*rob 2 node.js amazon-dynamodb

我正在寻找AWS dynamodb的DocumentClient节点中的一个非平凡的upsert示例.有人可以共享一个适合他们的样本吗?

我想看一个在创建记录时设置created_at,updated_at和id字段的示例,但只在找到并更新记录时设置updated_at.

gee*_*use 6

这应该达到你的目标.我很抱歉,因为我在原帖中错过了你的标准.我假设id是你桌子上的钥匙.

'use strict';

var AWS = require('aws-sdk');
var ec2 = new AWS.EC2({ apiVersion: '2016-09-15' });
var ddb = new AWS.DynamoDB.DocumentClient();
AWS.config.region = 'us-east-1';

var ret = {};
const ddbTbl = 'table_name';

var date = new Date();
var dateAsIso = date.toISOString();

exports.handler = (event, context, callback) => {
    var key = 'bar';
    var params = {
        TableName: ddbTbl,
        Key: {
            "id": key
        },
        UpdateExpression: "set #u = :t, #c = if_not_exists(#c, :t)",
        ExpressionAttributeNames: {
            "#u": "updated_at",
            "#c": "created_at"
        },
        ExpressionAttributeValues: {
            ":t": dateAsIso
        },
        ReturnValues: "UPDATED_NEW"
    };
    ddb.update(params, function(err, data) {
        if (err) {
            console.log(err, err.stack);
            ret.ddbUpdate = err;
            callback(null, {success: false, message: ["ddb upsert failed"], payload: ret});
            // or use the regular callback for failures if you don't want to do your own envelope response
        } else {
            console.log(data);
            ret.ddbUpdate = data;
            callback(null, {success: true, message: ["ddb upsert succeeded"], payload: ret});
        }
    });
};
Run Code Online (Sandbox Code Playgroud)