Sails JS - Waterline ORM - Query Date only, not Time - sails.js

Looking to query against the date only anyone encountered this?
Sample code:
////MODEL
module.exports = {
attributes: {
date: {
type: 'date',
required: true
}
}
};
////CONTROLLER
var today = moment().toISOString();
var queryObj = { date: today };
var newDay = { date: today };
Day.findOrCreate(queryObj, newDay).exec(function(err, day) {
console.log(day)
});
Obviously this creates a new record on each refresh, as the iso string will change with each passing second.
Thanks for the help!

Instead of querying for a single date, you can query for a date range that includes all of today. First, you'll need to actually create values for that range--I whipped this up using Moment, but there's probably a better way:
var begin = moment(moment().format("YYYY-MM-DD")).toISOString();
var end = moment(moment().format("YYYY-MM-DD")).add(1, 'days').toISOString();
Then you can use query operators to search the range:
var queryObj = {date: {'>=': begin, '<': end}};
Day.findOrCreate(queryObj, newDay).exec(function(err, day) {
console.log(day)
});
As always, be mindful of time zone issues!

Related

Rally: Date User Story is Defined

I am writing a program that needs to fetch user stories that are defined before day 3 of a release. Is there a way to find out what day a user story was set to the 'defined' state so that I could query that?
I looked through the Web Service API docs but I couldn't find anything that could help me, although I could have missed something.
This is the code I am using to get the 3rd day of a release:
var releaseStart = combobox.getRecord().get('ReleaseStartDate');
releaseStart.setDate(releaseStart.getDate()+3);
this._startDate = Rally.util.DateTime.toIsoString(releaseStart);
But I'm not sure how to relate this to the date a user story is defined.
If anyone could help it would be much appreciated!
You're right- this piece of data does not exist in the standard WSAPI. You can get it from LookbackAPI however. How about something like this to get started?
var releaseStart = combobox.getRecord().get('ReleaseStartDate');
var startDate = Rally.util.DateTime.add(releaseStart, 'day', 3);
var snapshotStore = Ext.create('Rally.data.lookback.SnapshotStore', {
context: {
workspace: this.getContext().getWorkspaceRef()
},
find: {
_ProjectHierarchy: this.getContext().getProject().ObjectID,
_TypeHierarchy: 'HierarchicalRequirement',
ScheduleState: {$gte: 'Defined'},
__At: startDate
},
sort: {
_UnformattedID: 1
},
fetch: ['FormattedID', 'Name', 'ScheduleState'],
limit: Infinity,
autoLoad: true,
listeners: {
load: function(store, records) {
//TODO: work with records here
}
}
});
More information on working with the Lookback API is here: https://help.rallydev.com/apps/2.1/doc/#!/guide/lookback_api

Store and Retrieve Date in dd MMM yyyy format in MongoDB model

I have a MongoDB model that contains a Date field whose type is defined as Date.now. Any date is converted to ISO date format. Inside the model the date is defined as :
xDate : {
type: Date.now,
required: true
}
I pass the current Date as :
var d = new Date();
var temp = d.toISOString();
var subStr = temp.substr(10,temp.length - 1);
var curDate = temp.replace(subStr, "T00:00:00.000Z");
console.log(curDate);
However the date is stored as an ISO String inside the MongoDB schema. I try to query it using Mongoose using the following query:
X.
find({
xDate: curDate
})
.exec(function(err, doc) {
var response = {
status : 200,
message : doc
};
if (err) {
console.log('Error');
response.status = 500;
response.message = err;
} else if (!doc) {
console.log("Documents against the date not found in database" ,curDate);
response.status = 404;
response.message = {
"message" : "Documents not found for " + curDate
};
}
res
.status(response.status)
.json(response.message);
});
I keep getting a blank json array inspite of the data being there. Inside the table the xDate is stored as YYYY-MM-DD format.
The date inside mongo is not stores in ISO string. If you save your model as Date.now, it will save a new Date object, not an ISO string. So one easy way of querying is to query by new Date() object.
Also note that your query is hard to be true, since you will have a hard time getting the exactly same date as your data is stored. I think better option for you is using $lt or $gt filters.
New query should look something like:
let currDate = new Date()
// change the date using class methods
X.find({
xDate: {$lt: currDate}
}).exec...

meteorhacks:aggregate to group mongo documents

This Meteor server code tries to count all the records which are 4 months and newer with property size:'4', color:'white' but account all entires from any one user as one count, so no mater how many documents have been entered by the same user, the are all counted as one. but I am getting nothing in return. any ideas? thx
let date = new Date();
date.setMonth(date.getMonth() - 4);
let doc = UsageCol.aggregate([{
$match: {
createdAt: {
$gte: date,
$lte: new Date()
},
action: 'failBroadcast',
plate: plate
}
}, {
$group: {
_id: {
userId: "$userId"
},
count: {
$sum: 1
}
}
}]);
for (var i = 0; i < doc.length; i++) {
var obj = doc[i];
console.log(JSON.stringify(obj));
}
Alright I just wanted to clear some things up from this morning.
The only reason I recommended moment js was thinking we are storing the date in date type and there is no easy way to dynamically create date in UTC using java script date function
So now that we know you used Date.now() to save the dates, you don't need any moment js.
The correct syntax is
let dateToMillis = Date.now(); //The current millis from epoch.
let dateFrom = new Date(dateToMillis); // Use the current millis from epoch.
let dateFromMillis = dateFrom.setMonth(dateFrom.getMonth() - 4); // The millis 4 months ago from epoch.
Pass dateToMillis and dateFromMillis to aggregation query.

Error with setting variable in property name in Mongo when using query

I have a collection called Programs in Mongo where one document looks like this (I'm in Meteor):
{ id: "gMyxyez43sxya",
.
.
Teachers: {
Week1: { Sunday: "SAM", Monday: "GEORGE" },
Week2: { Sunday: "FIONA", Monday: "JEFFERS" }
},
CampYear: "ssipc16",
}
The "Week1", "Week2" properties I need as a variable. The variable is calculated here:
var week = "Week" + Session.get('CurrentWeek').substr(0, 1); //this would render 'Week1', for example
var teacher = document.getElementById('sunday').value;
The query that I would need is this:
Programs.find({ "Teachers.week.Sunday": teachers });
But that won't work. So I built the object like this:
var query = { Teachers: {} };
query.Teachers[week].Sunday = teacher;
Then:
Programs.find(query).count();
But I'm getting a type error 'Uncaught TypeError: Cannot set property 'Sunday' of undefined'.
I also tried it like this:
query.Teachers[week] = { 'Sunday': teacher };
Programs.find(query).count();
There's no error but it keeps calculating a count of 0 every time.
How to make this work?
I found the solution: I needed to build it like this:
var teacher = document.getElementById('sunday-lessons-students').value;
var week = "Week" + Session.get('CurrentWeek').substr(0, 1);
var query = {};
query['Teachers.' + week + '.Sunday'] = teacher;
console.log(Programs.find(query).count());

Date Filter in sapui5

I have used two date controls to filter a row repeater as,
oF_cell5 = new sap.ui.commons.layout.MatrixLayoutCell({id:"F05",colSpan : 2});
var oCreateFrom = new sap.ui.commons.DatePicker("EV_AE_DATE1",
{width:"150px",placeholder:"Created From",
change:function(oEvent){
oController.onChangeFilterValue(oEvent);}
})
oF_cell51 = new sap.ui.commons.layout.MatrixLayoutCell({id:"F051",colSpan : 2});
var oCreateTill = new sap.ui.commons.DatePicker("EV_AE_DATE2",
{width:"150px",placeholder:"Created Till",
change:function(oEvent){
oController.onChangeFilterValue(oEvent);}
});
Now i have a rowrepeater in which one of the column is CreatedOn date like..,,
new sap.m.HBox({
items:[new sap.ui.commons.TextView({text:"Created on:"}),
new sap.ui.commons.TextView("TV11")
.bindProperty("text",
{
path: "CM_EventList>CREATEDON",
type: new sap.ui.model.type.Date({pattern:"MMM dd, yyyy",
source : {pattern : "dd.MM.yyyy"}})
})]
}),
And in the controller i have written this code as....,,
onInit: function() {
var model = new sap.ui.model.json.JSONModel("eventlist.json");
model.setData();
sap.ui.getCore().setModel(model,"CM_EventList");
},
onChangeCmFilterValue : function(oEvent){
var CM_FDATEVAL = sap.ui.getCore().byId("EV_AE_DATE1").getValue();
var CM_TDATEVAL = sap.ui.getCore().byId("EV_AE_DATE2").getValue();
var CM_Date = new sap.ui.model.Filter('CM_EventList>CREATEDON',
sap.ui.model.FilterOperator.BT,CM_FDATEVAL,CM_TDATEVAL);
var oCM_VBOX1 = sap.ui.getCore().byId("EV_CM_VBOX");
var oCM_RR1 = sap.ui.getCore().byId("EV_AE_ROWREPEATER");
oCM_RR1.bindRows('CM_EventList>/eventlist',oCM_VBOX1,null,[CM_Date]);
},
And the eventlist is my seperate json file which has date values as
{
"eventlist": [
{
"CREATEDON": "10.07.2014",
},
{
"CREATEDON": "10.08.2014",
},
.......
and so on..........
Now if select a date range from my date controls then the row repeater should show the records which are between the range of dates as in my json.
But the filter is not working.
Please Help me on this.
Thanks
Sathish
First of all, use the DatePicker Control for date fields in your view if you aren't using it already.
You can obtain the value of your date picker as a Date object using the method GetDateValue(). You can then use these date objects to create a filter for a datetime field of your data model.
var dateFrom = this.getView().byId("filterDateFrom").getDateValue();
var dateTo = this.getView().byId("filterDateTo").getDateValue();
if (dateFrom != null && dateTo != null) {
filter = new sap.ui.model.Filter(
"CM_EventList>CREATEDON",
sap.ui.model.FilterOperator.BT,
dateFrom,
dateTo
);
}
By the way: Note that both date objects will actually represent the moment at the beginning of the day (0:00:00) while the timestamps in your database will often be some point in time throughout the day. So when you want to search between two dates inclusively, you need to add one day to dateTo:
dateTo.setDate(dateTo.getDate() + 1);
Another problem you might or might not have to deal with are timezones... and of course all the other falsehoods programmers believe about time.
I think you should check the value of the following. The format should be different than your json value "CREATEDON": "10.08.2014".
var CM_FDATEVAL = sap.ui.getCore().byId("EV_AE_DATE1").getValue();
var CM_TDATEVAL = sap.ui.getCore().byId("EV_AE_DATE2").getValue();
Please try create a DatePicker with:
type: new sap.ui.model.type.Date({pattern: ""yyyy-MM-dd""})
Edit: to use Date as filter
var CM_FDATEVAL_DATE = new Date(sap.ui.getCore().byId("EV_AE_DATE1").getValue());
var CM_TDATEVAL_DATE = new Date(sap.ui.getCore().byId("EV_AE_DATE2").getValue());
Regards,
Allen