2017-08-23 14 views
1

私はDynamoDB UpdateItemを使用して自分のDB内のレコードを更新しています。このような基本的な機能が私のために働いています。DynamoDB:UpdateItem、ExpressionAttributeValuesのNull値を無視します。

var user = { 
    userID: '123213', 
    name: 'John Doe', 
    age: 12, 
    type: 'creator' 
}; 
var params = { 
    TableName:table, 
    Key:{ 
     "UserID": user.userID 
    }, 
    UpdateExpression: "set Name = :r, Age=:p, Type=:a", 
    ExpressionAttributeValues:{ 
     ":r":user.name, 
     ":p":user.age, 
     ":a":user.type 
    }, 
    ReturnValues:"UPDATED_NEW" 
}; 

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)); 
    } 
}); 

しかし...

私はこれだけのように一つの属性、名前、更新したい場合は:それは私にそのエラーを与える

var user = { 
     userID: '123213', 
     name: 'John Smith' 
    }; 
var params = { 
    TableName:table, 
    Key:{ 
     "UserID": user.userID 
    }, 
    UpdateExpression: "set Name = :r, Age=:p, Type=:a", 
    ExpressionAttributeValues:{ 
     ":r":user.name, 
     ":p":user.age, 
     ":a":user.type 
    }, 
    ReturnValues:"UPDATED_NEW" 
}; 

ExpressionAttributeValuesにNULLは指定できません。

私は動的にこのように、ユーザーの値をチェックしてUpdateExpression文字列を作り出すことができることを知っている:だけ

for (var key in user) { 
    if (user.hasOwnProperty(key)) { 
    ...add to DynamicUpdateExpression.. 
    } 
} 

を私はNULL値を無視するようにupdateItemを伝えることができる方法があるとnameを更新しますか?

答えて

2

私は同じ質問をしていました... JavaではSaveBehavior.UPDATE_SKIP_NULL_ATTRIBUTESがありますが、nodejのaws-sdkのようなものは見つかりませんでした。

const AWS  = require(aws-sdk); 
const bluebird = require('bluebird'); 
const _  = require('lodash'); 

AWS.config.setPromisesDependency(bluebird); 

const dynamodb = new AWS.DynamoDB.DocumentClient(); 

var skipNullAttributes = (attributes) => { 
    return _.omitBy(attributes, (attr) => { 
    return _.isNil(attr.Value); 
    }); 
} 

var update = (id, attributes) => { 
    var params = { 
    TableName  : 'MyTableName', 
    Key    : { id: id }, 
    AttributeUpdates: skipNullAttributes(attributes) 
    }; 

    return dynamodb.update(params).promise(); 
} 

exports.handler = (event, context, callback) => { 
    var body = JSON.parse(event.body); 
    var userId = event.pathParameters.id; 

    var attributes = { 
    firstName: { Action: 'PUT', Value: body.firstName }, 
    lastName : { Action: 'PUT', Value: body.lastName } 
    }; 

    update(userId, attributes) 
    .then((result) => console.log(result)) 
    .catch((error) => console.error(error)); 

    callback(null, {statusCode: 200, body: JSON.stringify({message: 'done!'})}); 
} 
+0

これは素晴らしい提案です:

あなたがきれいな回避策を作るためにAttributeUpdates代わりのUpdateExpressionを使用することができます。ありがとう。私は他の誰かが方法を見つけたかどうかを見るためにもう一日待つつもりです。 – inspired

+0

あなたはそれについて何かを見つけましたか?私は何も見つけることができませんでした。 –

+0

私は何も見つけられませんでした。私は吸血鬼になるつもりです。 – inspired

関連する問題