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
Related
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.
I am having a below json array and now I need to iterate over the json object to retrieve two values of fields ServicePort And ServiceAddress and form a final output as {"MyIp" : "http://IP:Port"} from my json array object.
var bodyObject = [
{
"ServiceAddress": "10.X.X.125",
"ServiceConnect": {},
"ServicePort": 80
},
{
"ServiceAddress": "10.X.X.126",
"ServiceConnect": {},
"ServicePort": 80
}
];
I have tried as below to iterate
for (var key in bodyObject ) {
if (bodyObject.hasOwnProperty(key)) {
console.log(bodyObject[key].ServiceAddress);
console.log(bodyObject[key].ServicePort);
}
}
How can I form a output final output like {"MyIp" : "http://IP:Port"} from my json array object each hitting giving me a diffrent Ip's from my above JSON list dynamically. Can someone help on this please
I think you're asking how to create a new array with a single object with a MyIp property whose value is the combination of ServiceAddress and ServicePort. map is the idiomatic way to do that, perhaps with some destructuring to pick out the properties from each object and a template literal to build the resulting string:
const result = bodyObject.map(({ServiceAddress, ServicePort}) => {
return {MyIp: `http://${ServiceAddress}:${ServicePort}`};
});
or with a concise-form arrow function:
const result = bodyObject.map(({ServiceAddress, ServicePort}) =>
({MyIp: `http://${ServiceAddress}:${ServicePort}`})
);
(You need the () around the object literal because otherwise it looks like the full function body form of arrow function to the parser.)
Live Example:
const bodyObject = [
{
"ServiceAddress": "10.X.X.125",
"ServiceConnect": {},
"ServicePort": 80
},
{
"ServiceAddress": "10.X.X.126",
"ServiceConnect": {},
"ServicePort": 80
}
];
const result = bodyObject.map(({ServiceAddress, ServicePort}) =>
({MyIp: `http://${ServiceAddress}:${ServicePort}`})
);
console.log(result);
That has a fair number of newish JavaScript features in it, so just for clarity here's a version without destructuring or a template literal:
const result = bodyObject.map(element => {
return {MyIp: "http://" + element.ServiceAddress + ":" + element.ServicePort};
});
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;
});
I'm trying to create a dataset from an API backend I've set up in my project. I've already managed to group my api call on the date but now I need to check the length of each date array that is created by lodash.
How would I do this because every attempt I've tried so far has failed. The image I've included shows the console.log after I have grouped my result, it also shows the amount of entries in each array which is exactly what I want to retrieve.
Current code, I removed my attempt at solving this problem because I would only get back undefined results.
ngOnInit() {
this._estimateService.getEstimates()
.subscribe(estimateData => {
const groupedEstimateData = groupBy(estimateData, 'estimate_date');
console.log(groupedEstimateData);
});
}
Example of desired result:
2019-12-09, 47
2019-12-10, 6
etc
Image:
I'm not sure of what you mean by "checking the length".
Here is an example of your desired console.log output
ngOnInit() {
this._estimateService.getEstimates()
.subscribe(estimateData => {
const groupedEstimateData = groupBy(estimateData, 'estimate_date');
Object.entries(groupedEstimatesData).map(([date, estimatedData]) => {
// do what you want there with each line
console.log(date, estimatedData.length);
});
});
}
You can have a look at Object.entries and map methods.
Good luck
You could do something like:
const groupsWithCounts = Object.keys(groupedEstimateData).map(key => {
[key]: groupedEstimateData[key],
total: groupedEstimateData[key].length
})
Now groupsWithCounts will be an array of objects with this structure:
{
2019-12-9: [item, item, item, ...], // the original items
total: 47 // the total count of items
}
You can do this simply with :
const dates = Object.keys(groupedEstimateData);
let output = {};
dates.forEach( date => output[date] = groupedEstimateData[date].length );
Object.keys(groupedEstimateData) will give you an array ["2019-12-09", "2019-12-10", etc]
You then iterate this array to construct this output object :
{
"2019-12-09" : 47,
"2019-12-10" : 6,
etc
}
I am trying to find a way to sort posts into two arrays: upcoming and current (upcoming posts are in the future and current have already been posted).
All posts have a scheduledPubDate that is a date string in the format YYYY-MM-DDT00:00:00. and todays date has to be a Date object as it will need to stay relevent (I am using moment())
Is it possible to compare these two different things without having to use a .split and compare the month / day /year separately
angular.forEach(data.items, function (key, index) {
if (moment(key.scheduledPubDate) > moment()) {
$scope.upcomingPosts.push(item[index]);
} else if (moment(key.scheduledPubDate) <= moment()) {
$scope.currentPosts.push(item[index]);
};
});
Presumably you want the string treated as UTC, a simple parser for that is:
// Expected format YYYY-MM-DDT00:00:00
function parseUTC(s) {
var b = s.split(/\D/);
return new Date(Date.UTC(b[0], b[1]-1, b[2], b[3], b[4], b[5]));
}
Note that this doesn't allow for invalid dates. If needed, an extra line if code is required. So now you can do:
if (parseUTC(key.scheduledPubDate) > new Date()) // or Date.now()
You really don't need moment.js for this.
JavaScript's built-in Date object will help you here.
var date = Date.parse('2014-01-21T12:45:13');
date < Date.now() // true
For the purpose of an example, let's assume items is an array of posts:
var items = [{
scheduledPubDate: '2014-01-21T12:45:13'
// ...other keys here
}, {
scheduledPubDate: '2017-03-01T15:21:00'
} // ...and so on
];
Then a reduce operation over items can categorize the posts:
var posts = items.reduce(function (memo, item) {
memo[Date.parse(item.scheduledPubDate) <= Date.now() ? 'current' : 'upcoming'].push(item);
return memo;
}, { current: [], upcoming: [] });
Now posts.current will contain an array of all posts from items whose scheduledPubDate is before the current date, and posts.upcoming will contain an array of all scheduled posts.
Edited to use Date.parse, to avoid unreliable behavior pointed out by RobG. This requires that all dates be in the YYYY-MM-DDT00:00:00 format you specified; if that is not the case, another solution will be required.
You have to specify the date format of the string
var format = "YYYY-MM-DDT00:00:00";
angular.forEach(data.items, function (key, index) {
if (moment(key.scheduledPubDate, format) > moment()) {
$scope.upcomingPosts.push(item[index]);
} else if (moment(key.scheduledPubDate, format) <= moment()) {
$scope.currentPosts.push(item[index]);
};
});
Working example (See the console.log): http://jsbin.com/fejaxiguce/1/edit?html,output
First create an array of elements, in any order, and then use the .sort() method.
http://www.w3schools.com/jsref/jsref_sort.asp
var points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return a-b});
Just substitute the above logic with your own. a and b above can be objects.