首页 > 解决方案 > 从 LAMBDA 触发器更新 DynanoDB

问题描述

每当表上发生事件时,我试图使用带有一些值的 lambda 触发器更新我MODIFY的表,但即使触发了该函数,更新查询也不会运行,并且更改不会反映在 dynamodb 中,并且CloudWatch没有显示有关的错误日志更新我已经为我的 Lambda 提供了AmazonDynamoDBFullAccessAWSLambdaDynamoDBExecutionRole权限。代码不适用于更新。

var AWS = require('aws-sdk');
// extra
const docClient = new AWS.DynamoDB.DocumentClient();

exports.handler = async (event , context , callback) => {
    // TODO implement
    
    event.Records.forEach((record) => {
        console.log('Stream record: ', JSON.stringify(record, null, 2));
        // logic to find insert type / modify type 
        //if(record.eventName == 'MODIFY' || record.eventName == 'INSERT'){
        if(record.eventName == 'MODIFY'){
             // extract student id, and marks from event itself (save I/O)
            console.log("Printing new image values",JSON.stringify(record.dynamodb.NewImage,null,2));
             // modify the same record once new value is calculated
             
             //############# code for pushing to DynamoDB #################
                 var params = {
                 TableName:'my-table name',
                 Key:{
                 "student_id": 'abc_123'
    },
    UpdateExpression: "set score1 = :r",
    ExpressionAttributeValues:{
        ":r":88
         },
    ReturnValues:"UPDATED_NEW"
};

console.log("Updating the item...");
docClient.update(params, function(err, data) {
    if (err) {
        console.error("Unable to update item. Error JSON:", JSON.stringify(err, null, 2));
    } else {
        console.log("UpdateItem succeeded:", JSON.stringify(data, null, 2));
    }
});

             //############# end of code ###############
        }
        
    });
    
    console.log(event);
    const response = {
        statusCode: 200,
        body: JSON.stringify(event),
    };
    
    
    
    return response;
};

我哪里错了?

谢谢您的帮助 !!

标签: node.jsamazon-web-servicesaws-lambdaamazon-dynamodbserverless

解决方案


由于您使用的是异步处理程序,我认为问题在于您的函数在处理程序的主体有机会运行之前完成。

纠正此问题的一种方法是使用AWS 文档Promise中所示的技术。


推荐阅读