Syntax error with $regex
I am trying to search for database records from the previous year using this code:
codevar getYear = (new Date()).getFullYear();
var yr = getYear-1;
var sYear = yr.toString();
//alert(sYear);
console.log("date = " + sYear);
var whereObject ={
Code: Select all
"$or": [
{"Date":{"$regex":sYear*,"$options":"i"}},
{"Date":{"$regex":sYear$,"$options":"i"}}
]
};
return JSON.stringify(whereObject);/code
I am searching a column called "Date" but it is a string type. Some dates are formatted as yyyy-mm-dd and some are mm/dd/yyyy. Therefore, I need to search
the beginning and the end.
Unfortunately, this code returns everything in the database whether it matches or not.
However, I found that I get the right results when I hard code the year in like this:
code{"Date":{"$regex":2016*,"$options":"i"}},
{"Date":{"$regex":2016$,"$options":"i"}}/code
So basically, I have some small syntax issue when I try to use a variable instead of an actual value. Any ideas on how to make this work?