语法:
- [Remove action[,action]...]——从项目中删除属性
- [DELETE action[,action]...]——从集合中删除元素/项目
- 删除项目
您可以使用 delete 方法,通过指定项目的主键来删除一个项目。您可以提供一个 ConditionExpression 以防止在不符合条件时删除项目。
var AWS = require('aws-sdk'); var fs = require('fs'); var uuid = require('uuid'); AWS.config.update({ region: "us-west-2", endpoint: "http://dynamodb:8000" }) var docClient = new AWS.DynamoDB.DocumentClient(); exports.handler = async function( event, context, callback ){ response = { headers: { "Content-Type": 'application/json', "Access-Control-Allow-Origin": "*", "Access-Control-Allow-Credentials": true, "Access-Control-Allow-Headers": "Content-Type, Access-Control-Allow-Headers, Access-Control-Allow-Origin, Authorization, X-Requested-With" }, } case 'DELETE': { var table ='book_table', hash = 'book'; id = 'bee1bea0-4b6a-4fbc-8cf0-8c030519c909'; var params = { TableName: table, Key: { "hash": hash, "id": id }, ConditionExpression: "price < :h", ExpressionAttributeValues: {":h" : 50}, await docClient.delete( params ).promise().then( ( data ) => { response.body = JSON.stringify({"success": data}); console.log("success", data ); } ).catch( ( err ) =>{ console.log("error", err ); response.statusCode = err.statusCode; response.body = JSON.stringify({"error": err}); } ); callback( null, response ); break; }}
- 添加集合
1 var AWS = require('aws-sdk'); 2 var fs = require('fs'); 3 var uuid = require('uuid'); 4 5 AWS.config.update({ 6 region: "us-west-2", 7 endpoint: "http://dynamodb:8000" 8 }) 9 10 var docClient = new AWS.DynamoDB.DocumentClient(); 11 12 exports.handler = async function( event, context, callback ){ 13 14 response = { 15 headers: { 16 "Content-Type": 'application/json', 17 "Access-Control-Allow-Origin": "*", 18 "Access-Control-Allow-Credentials": true, 19 "Access-Control-Allow-Headers": "Content-Type, Access-Control-Allow-Headers, Access-Control-Allow-Origin, Authorization, X-Requested-With" 20 }, 21 } 22 23 case 'POST': { 24 var table = "book_table", hash = "test"; 25 26 var params = { 27 TableName: table, 28 Item: { 29 "hash": hash, 30 31 "id": uuid(), 32 33 "book_type": docClient.createSet(["青春文学", "历史典故", "杂志", "小说"]) 34 } 35 36 }; 37 await docClient.put( params ).promise().then( 38 ( data ) => { 39 response.body = JSON.stringify({"success": data}) 40 } 41 ).catch( 42 ( err ) =>{ 43 response = { 44 statusCode: err.statusCode, 45 body: JSON.stringify({ 46 code: err.code, 47 message: err.message 48 }) 49 } 50 } 51 ) 52 53 callback( null, response ); 54 break; 55 } 56 }
程序运行成功后返回:
1 { 2 "success:": { 3 "Attributes": { 4 "book_type": { 5 "wrapperName": "Set", 6 "values": [ 7 "历史典故", 8 "小说", 9 "青春文学", 10 “杂志” 11 ], 12 "type": "String" 13 }, 14 "hash": "test", 15 "id": "87de4a25-7361-4fcf-af01-5949c55099a3" 16 } 17 } 18 }