1

I have a doubt, I have save some dates like this, timeStamp: "2014-10-30T15:13:37.199Z", in mongoose.

But I want to make a search like this:

model.find({ timeStamp: { $gte: startDate, $lt: endDate }})

Where startDate and endDate are for example 2014-10-30. Is that possible.

Diego
  • 493
  • 1
  • 9
  • 26
  • Yes I think you can use. But if you use `2014-10-30` for both of them fields Mongoose may convert to `2014-10-30T00:00:00.000Z`. So I think you can use `2014-10-30T00:00:00.000Z` for `startDate` and `2014-10-30T23:59:59.999Z` for `endDate` – efkan Feb 28 '15 at 08:47
  • Thanks for the answer, now if use the new Date command from node how can I discount the hours until midnigth, for example if I use new Date I obtain 2015-02-28T12:17:37.199Z how can I calculate to 2015-02-28T00:00:00Z? – Diego Feb 28 '15 at 15:20

1 Answers1

0

I should write here because of better code view.

if your date field has a string value you can use only;

startDate = startDate + "T23:59:59";

else;

startDate.setHours(23)
startDate.setMinutes(59)
startDate.setSeconds(59)

Node.js and Mongoose allows use Javascript date functions. So if you want, you might visit http://www.w3schools.com/jsref/jsref_obj_date.asp

Please, let me know your results.

efkan
  • 12,991
  • 6
  • 73
  • 106
  • I'll try what you indicate me, but is there anyway to search only by date, like this 2015-02-28 without the time, although mongoose have saved the date with time like this 2015-02-28T12:17:37.199Z? – Diego Feb 28 '15 at 16:19
  • If your date field has defined as a `Date`, Mongoose save values as a `ISODate()` for this field. Actually this is the main purpose of Mongoose (Object Data Mapping). Actually you can query your collection using `aggregate` function by year, month and day. Here is an answer; http://stackoverflow.com/a/8136834/3765109 Is it eligible to you? – efkan Feb 28 '15 at 17:08
  • Thanks for your answers I will try them and comment how it works. – Diego Feb 28 '15 at 21:01
  • Unfortunately there is no a short way in MongoDB to query just date values. If you working on logical design level of your app or whatever, you might divide and store your date as year, month and day fields. It's a very simple way. – efkan Mar 01 '15 at 05:34