Reputation: 108
In my MongoDb (using Mongoose) I'm storing dates as a string in utc and ISO format. Now I want to do a search for records by date but I can't figure out how.
Data.find()
.$where(function() {
return new Date(this.timeStamp).getTime() > new Date('2016-1-1').getTime();
})
.exec(function(err, wData) {
if(err) {return next(err);}
res.json(wData);
});
Problem is the $where removes all general functions for some reason and "getTime()" is not a method of the object.
How would I go about doing this without changing the schema to store a 'Date'.
Edit: I have also tried Date.parse(). And ' console' does not exist in the $where either if I try output anything.
Edit2: Here's my Schema, I don't have access to my Db at the moment so I can't give a sample doc. However, I am using the data already (without the $where, it just returns everything I have) and the date formats are fine and convert into Date objects correctly on the front end.
var WeatherData = new mongoose.Schema({
timeStamp: String,
lightLevel: Number,
temperature: Number,
pressure: Number,
humidity: Number,
windSpeed: Number,
windDirection: Number
});
Edit3: Although the problem is solved, I'm interested in any other methods that don't involve 'RegExp'
Upvotes: 0
Views: 1169
Reputation: 454
You can query dates using regex, try:
WheaterData.find( {timeStamp: new RegExp("^YYYY-MM-DD","i") } )
It will return all documents matching the given day in YYYY-MM-DD format.
Upvotes: 2