简体   繁体   中英

Mongoose.js find yesterday's date in database

I want to find all the users created up until yesterday. This is my code to make the query string:

var today = new Date();
var a = today.getDate();
a--;
today.setDate(a);
var yesterday = today.toDateString();

and it returns something like: Sun Jan 17 2016... which IS yesterday's date, but the db stores the date in iso format like: "date" : ISODate("2016-01-13T13:23:08.419Z") so what I get is 2016-01-13T13:23:08.419Z . My problem now is that I can't use the yesterday variable to query the db for the users I need AND even if I could, I don't know how to find every registration not including the ones that took place today.

Any help? Thank you very much!

You are generating a date on the front end, and then pushing it back a day, which is totally fine for a lot of circumstances -

For this, since you are trying to find DB entries that occured, perhaps try querying the database with a timestamp ranged pulled from the ID's of each document in your database.

Here is some documentation on how to do that from mongoDB. https://docs.mongodb.org/v3.0/reference/method/ObjectId.getTimestamp/

I've also provided some additional resources that may help you figure out exactly what to query in regard to this method:

https://steveridout.github.io/mongo-object-time/

https://gist.github.com/tebemis/0e55aa0089e928f362d9

Some psuedo code:

1. Query documents in the database
2. Get a timestamp from the ID's of the documents in the database
3. Set a range of the timestamps
4. Compare returned timestamps vs a timestamp range variable (yesterdays date in this case)
5. Have the DB return only documents that are within the range

I hope this helps!

Try this, using Moment.js :

yesterday = moment().add(-1, 'days');
db.users.find({ "date": { "$lt": yesterday }});

Create a date object that represents the start of day today, use it to query your collection for documents where the date field is less than that variable, as in the following example

var start = new Date();
start.setHours(0,0,0,0);

db.users.find({ "date": { "$lt": start }});

This will look for users created up until end of day yesterday.

momentjs is a super handy utility for doing manipulations like this. Using the library, this can be achieved with the startOf() method on the moment's current date object, passing the string 'day' as arguments:

Local GMT:

var start = moment().startOf('day'); // set to 12:00 am today
db.users.find({ "date": { "$lt": start }});

For UTC:

var start = moment.utc().startOf('day'); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM