node.js AWS dynamodb updateItem [英] node.js AWS dynamodb updateItem

查看:34
本文介绍了node.js AWS dynamodb updateItem的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法用updateItem实现以下几点:1.如果DynamoDB中不存在属性,则添加属性2. 如果属性存在于 DynamoDB 中,则更新属性3. 如果参数中不包含这些属性,则保留这些属性的原样.

Is there is way to achieve the following few points with updateItem: 1. Add attributes if the attributes not exist in DynamoDB 2. Update attributes if the attributes exist in DynamoDB 3. Leave those attributes as what they are if the attributes are not contained in the params.

这是一个例子:这是 DynamoDB 中的对象:

Here is an example: This is the object in DynamoDB:

{
    id: "1234",
    variable1: "hello",
    variable2: "world"
}

这是我希望更新的输入:

Here is the input that I wish to update:

{
    id: "1234",
    variable1: "hello2",
    variable23: "dog"  // the variable name "variable23" could be anything
}

这是我想要实现的 DynamoDB 中的更新项:

Here is the updated item in the DynamoDB that I want to achieve:

{
    id: "1234",
    variable1: "hello2",
    variable2: "world",
    variable23: "dog"
}

variable23"可以是任何变量名作为输入.

The "variable23" could be any variable name as input.

请帮忙!我使用 node.js,如果有人能告诉我一些如何实现这一点的代码,我真的很感激.

Please help! I use node.js, I really appreciate if anyone can show me some code how to achieve this.

谢谢!

推荐答案

这正是 AWS.DynamoDB.DocumentClient 的 update 方法所做的.

This is exactly what AWS.DynamoDB.DocumentClient's update method does.

已经有关于如何使用 update 方法的示例代码 此处 适用于 Node.js 中的适用于 JavaScript 的 AWS 开发工具包.

There is already a sample code on how to use the update method here for AWS SDK for JavaScript in Node.js.

例如:

'use strict';

const aws = require('aws-sdk');

// It is recommended that we instantiate AWS clients outside the scope of the handler 
// to take advantage of connection re-use.
const docClient = new aws.DynamoDB.DocumentClient();

exports.handler = (event, context, callback) => {
    const params = {
        TableName: "MYTABLE",
        Key: {
            "id": "1"
        },
        UpdateExpression: "set variable1 = :x, #MyVariable = :y",
        ExpressionAttributeNames: {
            "#MyVariable": "variable23"
        },
        ExpressionAttributeValues: {
            ":x": "hello2",
            ":y": "dog"
        }
    };

    docClient.update(params, function(err, data) {
        if (err) console.log(err);
        else console.log(data);
    });
};

这篇关于node.js AWS dynamodb updateItem的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆