I need a data filtered by date but I am getting an error
Error ValidationException: The provided key element does not match the schema
My table has a primary key (only partition key) of id
.
async function fetchDatafromDatabase() { // get method fetch data from dynamodb var date = todayDate(); var params = { TableName: table, Key: { "date": date } }; let queryExecute = new Promise((res, rej) => { dynamoDB.get(params, function (err, data) { if (err) { console.log("Error", err); rej(err); } else { console.log("Success! get method fetch data from dynamodb"); res(JSON.stringify(data, null, 2)); } }); }); const result = await queryExecute; console.log(result); }
Advertisement
Answer
For getting an item from DynamoDB, we must pass primary key, in this case, its just partition key ‘id’ (assuming it is numeric and storing epoc date)
var documentClient = new AWS.DynamoDB.DocumentClient(); var date = Date.now(); console.log("date", date); var params = { TableName: "test2", Key: { id: date, }, }; documentClient.get(params, function (err, data) { if (err) { console.log("Error", err); } else { console.log("Success", data); } });
Complete Example to put an item and get it.
var documentClient = new AWS.DynamoDB.DocumentClient(); var date = Date.now(); documentClient.put( { TableName: "test2", Key: { id: date, }, }, function (err, data) { if (err) console.log("err", err); if (data) { documentClient.get( { TableName: "test2", Key: { id: date, }, }, function (errGet, dataGet) { if (errGet) { console.log("Error", errGet); } else { console.log("Success", dataGet); } } ); } } );