How to fix mongoose "gt" and "lt" not working - node.js

I'm trying to get all staff members within a given date range using mongoose ODM, but can't seem to find a way.
I tried using different date formats, but came up with storing ISO date in my db. Now it saves and retrieves dates as ISODate("2018-12-23T00:00:00Z") format.
But, what I want is to get all staff members using a date range given using $gte and $lte
/**
* Get all attendance of one member for a specific time frame(a month)
*
*/
module.exports.getAttendanceTimeFrame = function(params,callback){
console.log(new Date(params.frm).toISOString());
AttendanceStaff.find({staff_id: params.staff_id, date:{$gte:params.frm, $lte:params.to}},callback);
}
This gives nothing but this gives all staff members who signed that day
Model.find({date:'2018-12-22'},callback);

That's because your params are sending date+time, whereas gte and lte only take date. The output of your log console.log(new Date(params.frm).toISOString()); should show timestamp

A foolish question. Pardon me..
I actually found what was wrong with it.. It was a friggin TYPO
here is it we can implement this using different approaches
since we store only a date, the mongoose will automatically convert all values we provide to ISODate format (date+time). Its actually very good because a similar pattern for a date or a time. So simply we can use the above code i have given It will work fine
/**
* Get all attendance of one member for a specific time frame(a month)
*
*/
module.exports.getAttendanceTimeFrame = function(params,callback){
console.log(new Date(params.frm).toISOString());
AttendanceStaff.find({staff_id: params.id, date:{$gte:params.frm, $lte:params.to}},callback);
}
actually instead of staff_id: params.staff_id, all I had to do was params.id
because thats how I defined the staff_id in http GET req. which is /staff/:id/:frm/:to
anyways we can even use where to do this as well a different approach...
/**
* Get all attendance of one member for a specific time frame(a month)
*
*/
module.exports.getAttendanceTimeFrame = function(params,callback){
console.log(params.id);
AttendanceStaff.find({date:{$gte:params.frm, $lte:params.to}}).sort({date:-1}).where({staff_id:params.id}).exec(callback);
}
so that's it ...

Related

Change date format in dialogflow

I`m currently trying to build up a chatbot/agent with dialogflow and have honestly no knowledge about anything in the programming business/IT stuff. I´m a student who had a guestlecture where we were shown how to create Chatbots haha. But I was interested and sat down and tried to create one for my work. A simple bot that tells the customer about the opening times and gives out some information to save us some phone calls. So far so good. I want to include the function to book a table and my problem is the following:
I´ve read many questions about changing the date and time format to receive a format like "4pm on Thursday" instead of "2020-12-26T16:00:00+01:00".
So as I said I have no clue so far how the change the code to get a different output so my question would be if you could tell me where exactly I have to do that or where I can find a solution for that. Don´t get me wrong I´d love to know how to do it so yeah I´d be so happy if you could save that christmas present :)
Best regards
Mo
So, your question is vague and lacks details.
If you want to convert "2020-12-26T16:00:00+01:00" to "4pm on Thursday" in your local time here are helper functions to achieve that:
function convertParametersDateTime(date, time){
return new Date(Date.parse(date.split('T')[0] + 'T' + time.split('T')[1].split('+')[0]));
}
// A helper function that adds the integer value of 'hoursToAdd' to the Date instance 'dateObj' and return a new Data instance.
function addHours(dateObj, hoursToAdd){
return new Date(new Date(dateObj).setHours(dateObj.getHours() + hoursToAdd));
}
// A helper funciton that converts the Date instance 'dateObj' into a string that represents this time in English.
function getLocaleTimeString(dateObj){
return dateObj.toLocaleTimeString('en-US', {hour: 'numeric', hour12: true});
}
// A helper dunction that converts the Date instance 'dateObj' into a string that represents this date in English
function getLocaleDateString(dateObj){
return dateObj.toLocaleDateString('en-US', {weekday: 'long', month: 'long', day: 'numeric'});
}
Those are the helper functions. You have to call them inside the Fulfillment function for your intent. Here's a very simple example:
function makeAppointment (agent) {
// Use the Dialogflow's date and time parameters to create Javascript Date instances, 'dateTimeStart' and 'dateTimeEnd',
// which are used to specify the appointment's time.
const dateTimeStart = convertParametersDateTime(agent.parameters.date, agent.parameters.time);
const dateTimeEnd = addHours(dateTimeStart, appointmentDuration);
const appointmentTimeString = getLocaleTimeString(dateTimeStart);
const appointmentDateString = getLocaleDateString(dateTimeStart);
agent.add(`Here's the summary of your reservation:\nDate&Time: ${appointmentDateString} at ${appointmentTimeString}`);
}
The codes might include some syntax errors. Those functions give what you are looking for but you would have to adjust them according to your needs.

Error message "cannot find function getFullYear(...)" when entering date and trying to save the record

We are trying in a RESTLet to access the sublist "demandplandetail" from a NetSuite Item Demand Plan. Everything goes fine until a certain point. We are able to load it and process the demandplan for 2020. However, here it gets frustrating.
We know (can see from NetSuite) that there is data also for 2021. However, to access that from SuiteScript seems very difficult.
1st solution) The item demand plan has the field "year". OK, just set that to 2021, save and reload the record. Result: saving ignored, year still is 2020.
2nd solution) Set the year using a Date object as in:
var demandPlan = record.load(...)
var d = new Date();
demandPlan.setValue({
fieldId: 'year',
value: d
});
Gives the following:
:"TypeError: Cannot find function getFullYear in object NaN. (NLRecordScripting.scriptInit$lib#59)","stack":["setDatesForMonthAndYear(NLRecordScripting.scriptInit:108)","anonymous(N/serverRecordService)"
on saving the record. I also get the same using (various) strings adhering to acceptable date formats (as in '1/1/2021'). I have also tried the format package giving me a date string -> the same result.
Also read somewhere that you may need to set the start date (field 'startdate') in the record. Tried several variations but it stubbornly refuses :(.
Wonder if anyone has seen anything similar?
Best Regards,
Toni
Hi Please try the below code also check if you're passing date object to the field not the date string.
function formatDate() {
var dateROBD = format.parse({
value: new Date(),
type: format.Type.DATE
});
// this line optional if you want to try with or else ignore this
dateROBD = convertUTCDateToLocalDate(new Date(dateROBD));
return dateROBD;
}
function convertUTCDateToLocalDate(date) {
var newDate = new Date(date.getTime() + date.getTimezoneOffset() * 60 * 1000);
var offset = date.getTimezoneOffset() / 60;
var hours = date.getHours();
newDate.setHours(hours - offset);
return newDate;
}
OK, mystery solved. Turned out that this is not supported in SuiteScript 2.0 but you need to use 1.0.

How truncate time while querying documents for date comparison in Cosmos Db

I have document contains properties like this
{
"id":"1bd13f8f-b56a-48cb-9b49-7fc4d88beeac",
"name":"Sam",
"createdOnDateTime": "2018-07-23T12:47:42.6407069Z"
}
I want to query a document on basis of createdOnDateTime which is stored as string.
query e.g. -
SELECT * FROM c where c.createdOnDateTime>='2018-07-23' AND c.createdOnDateTime<='2018-07-23'
This will return all documents which are created on that day.
I am providing date value from date selector which gives only date without time so, it gives me problem while comparing date.
Is there any way to remove time from createdOnDateTime property or is there any other way to achieve this?
CosmosDB clients are storing timestamps in ISO8601 format and one of the good reasons to do so is that its lexicographical order matches the flow of time. Meaning - you can sort and compare those strings and get them ordered by time they represent.
So in this case you don't need to remove time components just modify the passed in parameters to get the result you need. If you want all entries from entire date of 2018-07-23 then you can use query:
SELECT * FROM c
WHERE c.createdOnDateTime >= '2018-07-23'
AND c.createdOnDateTime < '2018-07-24'
Please note that this query can use a RANGE index on createdOnDateTime.
Please use User Defined Function to implement your requirement, no need to update createdOnDateTime property.
UDF:
function con(date){
var myDate = new Date(date);
var month = myDate.getMonth()+1;
if(month<10){
month = "0"+month;
}
return myDate.getFullYear()+"-"+month+"-"+myDate.getDate();
}
SQL:
SELECT c.id,c.createdOnDateTime FROM c where udf.con(c.createdOnDateTime)>='2018-07-23' AND udf.con(c.createdOnDateTime)<='2018-07-23'
Output :
Hope it helps you.

Query by Date not working

I am trying to return search results for every document that was created on a day. Below is the query I use.
var query = Document.find({}).populate('contacts');
var gte = moment(req.query.date, 'DD-MM-YYYY').startOf('Day');
var lte = moment(req.query.date, 'DD-MM-YYYY').endOf('Day');
query.where('dates.createdAt').gte(gte).lt(lte);
This query works for some days but not all. I can't seem to understand the behaviour. Please help out.
The format of the date in the query string is DD/MM/YYYY.
Works for : 2016-04-16T00:02:30.065Z
Does not work for: 2016-04-15T19:02:59.758Z
It's wrong because you don't initialize as .utc(), and MongoDB dates are stored in UTC:
var gte = moment.utc(req.query.date, 'DD-MM-YYYY');
var lte = moment.utc(req.query.date, 'DD-MM-YYYY').endOf('Day');
And there is no need for the startOf() either.
If you don't construct like that, then the resulting Date object is skewed by the difference in the local timezone. Hence why you don't see the selection working where the hours would cross over dates.
Also if dates are coming in as 01/01/2016 then the format string would be 'DD/MM/YYYY', but one or the other is likely a typo in your question.

How can I easily access the MongoDB ObjectId date from within a templating engine?

At the moment using JavaScript I'm attaching a date to every single object similar to the following.
post.date = getTimestamp(post._id).toDateString();
I can then access 'date' from within my template. Is there a nicer way to extract the date?
I'm not sure if this will work in a template, but:
post._id.getTimestamp();
returns an ISODate.
http://mongodb.github.com/node-mongodb-native/api-bson-generated/objectid.html#gettimestamp
If _id is UUID, then first 8 bytes of it is timestamp.
You may, fore example, extract date as follows:
var date = new Date( parseInt( post._id.substring(0,8), 16 ) * 1000 )

Resources