Date request I mongo from node.js

I want to request a collection of mongo by date. Example:

var startDate = new Date(dateNow.getUTCFullYear(),dateNow.getUTCMonth(),dateNow.getUTCDate(),dateNow.getUTCHours(),0); var endDate = new Date(dateNow.getUTCFullYear(),dateNow.getUTCMonth(),dateNow.getUTCDate(),dateNow.getUTCHours()+1,0); query.timeRegistered = { '$gte' : startDate, '$lt' : endDate }; ... make mongo query ... 

But that will not work. I assume this is because mongo saves the date object in ISODate format. This request works from the shell because mongo converts Date to ISODate, but from javascript (node.js) it does not work. I tried all possible solutions, but none of them helped me.

Please, if anyone has any solution, I will be very grateful ....

+4
source share
1 answer

Note that the default date operation in Mongo is in UTC, for example. I entered the t1 collection entry on June 22, 2015 at 7:10 pm IST . however, in the shell you can see its value as "ISODate" ("2015-06-22T 13:40 : 08.545Z"), which is 5:30 hours behind, from your javascript code (which runs in the browser and therefore takes the browser time zone), try creating variable start and end dates according to the UTC time zone, and then request entries. Let us know if it doesn’t work, so it is simple, gives a very large date range and sees if it works or not. since I'm not a JS expert, I suppose you might have to tweak your dates to do this in UTC.

however, I tried with the Mongo client, as shown below, and it worked, so I assume that JS should also work as long as you pass the date in the correct time zone.


 db.t1.find({dt:{$gt:ISODate("2015-06-22T13:40:00.000Z"),$lt:ISODate("2015-06-22T13:41:00.000Z")} }) 
0
source

Source: https://habr.com/ru/post/1439410/


All Articles