compare current date with existing dates in Dynamodb table in nodejs - javascript

Contact center should not work on holidays so for that we are trying to add holiday list in dynamodb table(which has only one column "date") and write a lambda which will compare with the current date
If the date matches it has to return true
If the date does not match it has to return false
Using this link [https://www.fernandomc.com/posts/eight-examples-of-fetching-data-from-dynamodb-with-node/][1] reference i tried match the current date with existing values
but somehow it is returning Error:"UnexpectedParameter: Unexpected key '7' found in params.ExpressionAttributeValues[':date']"
Edited
Table : Partition key: date (String) and the format is YYYY-DD-MM
var dynamodb = new AWS.DynamoDB({ apiVersion: '2012-08-10' });
exports.handler = async (event) => {
let response = '';
var tableName = "table";
const currentdate = new Date().toISOString().split('T')[0];
try {
var params = {
KeyConditionExpression: '#D = :d',
ExpressionAttributeValues: {
':d': { S: currentdate }
},
ExpressionAttributeNames: {
'#D': 'date'
},
TableName: tableName
};
var result = await dynamodb.query(params).promise()
console.log(JSON.stringify(result))
return true;
} catch (error) {
console.error(error);
return false;
}
};

A couple of problems.
Your ExpressionAttributeValues has the incorrect syntax - you need to tell DynamoDB what data type the field is, like this:
ExpressionAttributeValues: {
':d': { S: currentdate }
},
date is a reserved word in DynamoDB, so you will need to add an ExpressionAttributeNames clause too, like this:
ExpressionAttributeNames: {
'#D': 'date'
}
Which also necessitates you changing the KeyConditionExpression to:
KeyConditionExpression: '#D = :d'
Double check the docs if need be.
And just in case you do actually store the date in YYYY-DD-MM format, an ISO date is YYYY-MM-DD. I'm just assuming this is a typo, however.

Related

Is there a way to use filterByFormula in Airtable to filter by a specific field value by date without it defaulting to the first entry in the table?

I am trying to filter by date to get one specific record, of which the Name field should = 8/01/2022. (I used the Name field in Airtable to place the dates. I set the field type to date.)
The issue I'm having is that although it seems to work fine, it basically ignores the specification for the date and instead returns the first value in the table.
This is what I have for getting the data from airtable.
let isoDate = new Date("08/01/2022").toISOString().slice(0, 10);
const base = new Airtable({ apiKey: apiKey }).base(baseID);
base("tabledata")
.select({
filterByFormula: `"DATESTR({Name})='${isoDate}'"`,
view: "Grid view",
})
.eachPage(
function page(records, fetchNextPage) {
records.forEach(function (record) {
let newEl = {
date: record.get("Name"),
game: record.get("games"),
};
setData(newEl);
});
try {
fetchNextPage();
} catch {
return;
}
},
function done(err) {
if (err) {
console.error(err);
return;
}
}
);
and this is the record that is retrieved:
{date: '2022-07-29', game: Array(6)}
date: "2022-07-29"
game: Array(6)
'2022-07-29' is the name of the first field in my table.
when I print the ISOString at any point I get 8/01/2022.
It turned out the issue was with this line
filterByFormula: `"DATESTR({Name})='${isoDate}'"`
I ended up changing the data type in airtable to short text since it doesn't really matter when it comes to the way I'm using it. So DATESTR was no longer needed, but I was still dealing with the issue no matter what I did.
Here is my new isoDate variable declaration:
let isoDate = new Date().toLocaleDateString();
It took me a while before I realized that it would make sense to try this line and see if it would work: "{Name})='8/01/2022'"
And it did! So clearly the issue was with the isoDate string.
After searching for a while I found this setup which worked:
filterByFormula: `{Name} = "${isoDate}"`
The main difference is the double quotes around the variable and no extra quotes around the full string.

get GroupBy count in Dexie

I have an IndexedDB table that follows accepts following structured JSON as a row:
{
id : 1,
name : 'doc1',
createdDate : '2018-08-08'
}
I want to get count for each available date in the table. ie: groupby:date then count. Expected example output is in the format of:
{
'2018-08-08' : 5,
'2018-08-18' : 19,
...
}
Table contains large number of records. So, how can efficiently achieve this requirement using Dexie?
If you index createdDate,
const db = new Dexie("yourDB");
db.version(1).stores({
yourTable: "id, name, createdDate"
});
Then you could do the following:
const result = {}
await db.yourTable.orderBy('createdDate').eachKey(date => {
result[date] = (result[date] || 0) + 1;
});

Dynamic variable in $in mongoose

I have following variables. (I am using this query in mongoose, node )
var splitDates=currentDate.split('-');//2019-12-09
currentDate=splitDates[0]+splitDates[1]+splitDates[2] //returns 20191209
previousDate= splitDates[0]+splitDates[1]+splitDates[2]-1;
I want it in the mongoDB query:
{ batchRef: { $in: [/20191209/, /20191210/] } }, // this is static values and works.
{ batchRef: { $in: ['/'+previousDate+'/','/'+currentDate+'/'] } }, // this doesnt work!
am I missing something?
any help would be appreciated.
This looks like a javascript date transformation question.
You can use the following code to get a string array for a given date and previous date to be used in $in query.
const inputDateString = "2019-12-09";
const currentDate = new Date(inputDateString);
const previousDate = new Date(inputDateString);
previousDate.setDate(currentDate.getDate() - 1);
let inArray = [];
inArray.push(inputDateString.split("-").join(""));
inArray.push(
previousDate
.toISOString()
.slice(0, 10)
.split("-")
.join("")
);
console.log(inArray);
inArray will have these 2 items:
[ '20191209', '20191208' ]
Now we can use this in the query like this:
{ batchRef: { $in: inArray } }
Please not that I assumed that inputDateString is always in this format with 10 characters, like 2019-01-31 or 2019-01-01

DeleteBy() Algolia

I am trying to simply delete an item inside Record in Algolia, but I can not achieve it.(Im working in Javascript)
My structure is the following in each record:
- title
- desc
- date
I want to delete each item in which the date is equal to (for example): 03/04/17
I was trying the following without good results:
var client = algoliasearch('-------', '-------');
var index = client.initIndex('------');
index.deleteBy({
date:'03/04/17',
}, function(err, content) {
if (err) throw err;
alert(JSON.stringify(content));
});
The date to delete by needs to be specified in the filter parameters and as a unix timestamp.
const date = new Date('03/11/17')
const unixDate = date.getTime() / 1000
//...
index.deleteBy({ filter: `date=${unixDate}` }, callback);

When emitting a date in a CouchDB Map function - what is being called on the date object?

I'm experimenting with emitting Date objects as the key in a map function, and can't understand what is happening when the Date object isn't parsed correctly.
Using a simple example record set :
{
"_id": "e3681a4f5ce5685b777659804e9fd9f1",
"date": "2016-04-04T16:02:09.058+01:00" // okay datestring
}
{
"_id": "99a5c50967a279e1d7fef1a4ed18d7fb",
"date": "2016-04-34T16:02:09.058+01:00" // invalid datestring
}
{
"_id": "43a435ce71a4b92ab0dd4fe9d91fbbb2",
"date": "text" // invalid datestring
}
And the following map function :
function(doc) {
var date = new Date(doc.date);
emit(date,1);
}
Gives the following result set :
{"total_rows":3,"offset":0,"rows":[
{"id":"43a435ce71a4b92ab0dd4fe9d91fbbb2","key":null,"value":1},
{"id":"99a5c50967a279e1d7fef1a4ed18d7fb","key":null,"value":1},
{"id":"e3681a4f5ce5685b777659804e9fd9f1","key":"2016-04-04T15:02:09.058Z","value":1}
]}
Where are the null values for the key coming from? It's not calling toString() or toISOString() on the dates as they would return "Invalid Date"
What's going on here?
Essentially, it works like this:
function emit(key, value) {
var row = { id: currentDocId(), key: key, value: value };
appendToOutput(JSON.stringify(row));
}
So it should be easy to see where the values come from, given that toJSON() on an invalid date returns null.
In reality it's not the emit() function that does this at all, but the default rendering implementation used when no list function is supplied.
while (row = getRow()) {
send(JSON.stringify(row))
}

Categories