Mongoose, Function Cannot Be Performed on Undefined, From Query Function - javascript

I am trying to use today's date as the field on which to
search - at this juncture, without having to worry about integrating the moment.js library. There will be only one record with today's date in the "table".
app.dashboardreport
.findOne()
.$where(function() {
return this.createdOn.toJSON().slice(0, 10) == Date.now().toJOSN().slice(0, 10);
})
.exec(function(err, foundDashboardReport) {
The $where function is throwing an error.
MongoError: TypeError: Cannot call method 'toJSON' of undefined
at _funcs1 (_funcs1:2:26) near 'createdOn.toJSON().slice(0, 10) == Date.n' (line 2)
It appears that "this" may not be defined; however, I know there is a record which meets those criteria.
Am I structuring the query incorrectly? If so, what needs to change in the function so that I can filter on that condition?

The problem, here, is a lack of understanding of the way in which data is structured in document-based storage. Each document must contain the createdOn field - if it is absent, then you will receive this error. this is defined; createdOn is not.
If you have data that is not uniform, you need to evaluate the presence of the field. So, it might look like this:
app.dashboardreport
.findOne()
.$where(function() {
/* The check for the field createdOn ensures that the compared document
does indeed contain the field */
return this.createdOn && this.createdOn.toDateString() == new Date().toDateString();
})
Note the addition of the this.createdOn evaluation in the return statement.

You get this error a CreatedOn is not present in every document. You could so something like this to get around this:
(this.createdOn|| new Date('31 Dec 9999')).toJSON()

Related

How does this left hand side assignment for a function call work in JScript?

I was looking for a way to log down messages the installer log using JScript and stumbled upon this answer:
How to debug an MSI Custom Action that is implemented in Javascript?
It works great. However there is something intriguing in the code that I haven't been able to figure out. In this method:
// spool an informational message into the MSI log, if it is enabled.
function LogMessage(msg) {
var record = Session.Installer.CreateRecord(0);
record.StringData(0) = "CustomAction:: " + msg;
Session.Message(MsgKind.Log, record);
}
How does the line record.StringData(0) = "CustomAction:: " + msg; work, from a syntax/semantic perspective? It looks to me this is trying to assign a value to the return value of a function call, which should be illegal or a no-op at best? Yet it works, and the message is printed out in the log.
What am I missing?
It is a JScript way to access lists and not an actual function. Therefore it does not throw an Invalid left-hand side in assignment.
StringData is a list of values. What you are actually setting is the value of the 0 index. It is like setting the value to an array using arr[0] = 'xyz'. In your example you could also omit it:
record.StringData = "CustomAction:: " + msg;
Syntax
propVal = Record.StringData
Record.StringData = propVal
Property value
Required field number of the value within the record, 1-based.
Remarks
The returned value of a nonexistent field is an empty string. To set a record string field to null, use either an empty variant or an empty string. Attempting to store a value in a nonexistent field causes an error.
Source: Patrick

length and typeof == undefined being ignored, lodash

Hopefully, my codepen is clear enough, first time using it - https://codepen.io/jsfo011/pen/GRojmpw
notEmpty is JSON from my database. I wrote a function to loop through it and find the row that matches a parameter, returning the value.
If my function can't find a matching row, I want to return 0.
I figured what I had written would work, but I keep getting
"jQuery.Deferred exception: Cannot read property 'total_income' of undefined" "TypeError: Cannot read property 'total_income' of undefined
But it seems to work fine when it does match.
What am I missing?
If income after filtering does not have a single value (empty list), single[0] is undefined. So, the following code was trying to access a property "total_income" of undefined
income[0]["total_income"]
You need to make sure that the property is accessed only if the parent object income[0] is valid.
One way to do this is by adding another check to make sure that income has at least a single value in the list before we access it like so:
if (income && income.length) {
if (income[0]["total_income"] !== undefined) {
return parseFloat(income[0]["total_income"]);
}
}
The line checks to make sure that income is defined and has at least one value.
Output:
Empty Data - 0
Found - 1000
Not found - 0
Hope this helps in understanding the issue.
why not just using lodash.get( ) with default value 0:
function calculate(data, income_type) {
let income = _.filter(data, {'income_type': income_type});
let incomeValue = _.get(income, '0.total_income', 0);
return parseFloat(incomeValue);
}

Object reference not set to an instance of an object - Model Binding [duplicate]

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
What does "Object reference not set to an instance of an object" mean? [duplicate]
(8 answers)
Closed 8 years ago.
I keep getting this error when I run the program.
Object reference not set to an instance of an object.
Description: An unhandled exception occurred during the execution of the current web request.
Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.
Source Error:
Line with error:
Line 156: if (strSearch == "" || strSearch.Trim().Length == 0)
What is the correct way it should be written?
The correct way in .NET 4.0 is:
if (String.IsNullOrWhiteSpace(strSearch))
The String.IsNullOrWhiteSpace method used above is equivalent to:
if (strSearch == null || strSearch == String.Empty || strSearch.Trim().Length == 0)
// String.Empty is the same as ""
Reference for IsNullOrWhiteSpace method
http://msdn.microsoft.com/en-us/library/system.string.isnullorwhitespace.aspx
Indicates whether a specified string is Nothing, empty, or consists
only of white-space characters.
In earlier versions, you could do something like this:
if (String.IsNullOrEmpty(strSearch) || strSearch.Trim().Length == 0)
The String.IsNullOrEmpty method used above is equivalent to:
if (strSearch == null || strSearch == String.Empty)
Which means you still need to check for your "IsWhiteSpace" case with the .Trim().Length == 0 as per the example.
Reference for IsNullOrEmpty method
http://msdn.microsoft.com/en-us/library/system.string.isnullorempty.aspx
Indicates whether the specified string is Nothing or an Empty string.
Explanation:
You need to ensure strSearch (or any variable for that matter) is not null before you dereference it using the dot character (.) - i.e. before you do strSearch.SomeMethod() or strSearch.SomeProperty you need to check that strSearch != null.
In your example you want to make sure your string has a value, which means you want to ensure the string:
Is not null
Is not the empty string (String.Empty / "")
Is not just whitespace
In the cases above, you must put the "Is it null?" case first, so it doesn't go on to check the other cases (and error) when the string is null.
All versions of .Net:
if (String.IsNullOrEmpty(strSearch) || strSearch.Trim().Length == 0)
.Net 4.0 or later:
if (String.IsNullOrWhitespace(strSearch))
strSearch in this case is probably null (not simply empty).
Try using
String.IsNullOrEmpty(strSearch)
if you are just trying to determine if the string doesn't have any contents.
I know this was posted about a year ago, but this is for users for future reference.
I came across similar issue. In my case (i will try to be brief, please do let me know if you would like more detail), i was trying to check if a string was empty or not (string is the subject of an email). It always returned the same error message no matter what i did. I knew i was doing it right but it still kept throwing the same error message. Then it dawned in me that, i was checking if the subject (string) of an email (instance/object), what if the email(instance) was already a null at the first place. How could i check for a subject of an email, if the email is already a null..i checked if the the email was empty, it worked fine.
while checking for the subject(string) i used IsNullorWhiteSpace(), IsNullOrEmpty() methods.
if (email == null)
{
break;
}
else
{
// your code here
}
I want to extend MattMitchell's answer by saying you can create an extension method for this functionality:
public static IsEmptyOrWhitespace(this string value) {
return String.IsEmptyOrWhitespace(value);
}
This makes it possible to call:
string strValue;
if (strValue.IsEmptyOrWhitespace())
// do stuff
To me this is a lot cleaner than calling the static String function, while still being NullReference safe!

Detect SQL min date string in javascript

In an angularJS application I'm working on, we are using a SQL server to provide data. Nothing odd there. I am tasked with working on the date sanitation, so objects that are passed into our application that have the SQL min date value are undefined, and ones that do have a date are javascript Date objects.
I know that during upgrades, sometimes the string that is defined for min date can change. Right now, it is 0001-01-01T00:00:00Z. I cannot just do a string comparison because it could change.
My problem is, how do i determine this min date in javascript? new Date(varThatIsMinDate) is a valid date. MomentJS thinks its valid too, and it is technically a valid date. I'm less worried about validation and more worried about "is it min date"
How do you determine min date === true from a zulu pattern 0001-01-01T00:00:00Z or similar in javascript?
My code so far, cause I know you are gonna ask for it:
if (response.config.responseType === 'json') {
for (var property in response.data) {
if (response.data.hasOwnProperty(property)) {
if (property.toUpperCase().indexOf('DATE') > -1 || property.toUpperCase().indexOf('TIME') > -1) {
console.log(property.toUpperCase());
// Attempt to use JS built in date and validate
var tmpDate = new Date(response.data[property]);
if ($moment(tmpDate).isValid()) {
// Make it a valid date object if it has a valid date
response.data[property] = tmpDate;
} else {
// Make it undefined
response.data[property] = undefined;
}
}
}
}
}
Thing is, its always valid, so this code doesn't work.
EDIT: I could cheat and use tmpDate.getUTCFullYear() === 1 but i'd like to know how to do this the right way.

Using a funcCall that retrieves multiple fields

Ello, I'm using jQuery-Validation-Engine and i don't know if this is currently possible but, Is there a way for you to possibly use the funcCall in a senario such as this.
I have to check a date range using 2 textboxes. I want to bind funcCall[dateRangeCheck] in such a way that I can get access
to 2 fields as opposed to just the one. The end result would would something like this.
dateRangeCheck = function (fields, rules, i, options) {
if (isDate(fields[0]) && isDate(fields[1])) {
if (!dateCompare(fields[0], fields[1])) {
return "* Invalid Date Range";
}
}
};
Or possibly all the fields that a utilizing this particular funcCall like this
dateRangeCheck = function (fields, rules, i, options) {
for (var i=0;i<fields.length;i++)
if(!isDate(fields[i]){
return "* Invalid Date Range";
}
}
};
Is there some way to accomplish this?
Well now jQuery-validation-engine does support date range checking. Just made the commit myself waiting for it to be reviewed. lol, But no to that second example as of now.
Here is the source. Have a nice day.
Update
The latest version does support group validation.

Categories

Resources