Mongoose.js在数据库中find昨天的date

我想查find昨天为止创build的所有用户。 这是我的代码,使查询string:

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

它会返回类似于:Sun Jan 17 2016 …哪个是昨天的date,但是db以iso格式存储date,如: "date" : ISODate("2016-01-13T13:23:08.419Z")我得到的是2016-01-13T13:23:08.419Z 。 我现在的问题是,我不能使用昨天的variables来查询数据库为我需要的用户,即使我可以,我不知道如何find每一个登记,包括今天发生的。

任何帮助? 非常感谢你!

你在前端生成一个date,然后把它推回到一天,这在很多情况下是完全正确的 –

为此,由于您正在尝试查找发生的数据库条目,因此可能尝试使用从数据库中每个文档的ID拉取的时间戳查询数据库。

这里是一些关于如何从mongoDB做到这一点的文档。 https://docs.mongodb.org/v3.0/reference/method/ObjectId.getTimestamp/

我还提供了一些额外的资源,可以帮助您找出究竟该查询什么方法:

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

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

一些伪代码:

 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 

我希望这有帮助!

创build一个表示今天开始的date对象,使用它来查询您的集合中的date字段小于该variables的文档,如下例所示

 var start = new Date(); start.setHours(0,0,0,0); db.users.find({ "date": { "$lt": start }}); 

这将会寻找昨天结束的用户。

momentjs是一个超级方便的工具来做这样的操作。 使用这个库,可以通过当前的date对象的startOf()方法来传递string'day'作为参数:

本地GMT:

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

对于UTC:

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

试试这个,使用Moment.js :

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