【问题标题】:Mongoose.js find yesterday's date in databaseMongoose.js 在数据库中查找昨天的日期
【发布时间】:2016-04-24 00:07:52
【问题描述】:

我想找到直到昨天创建的所有用户。这是我制作查询字符串的代码:

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

它返回类似:Sun Jan 17 2016... 这是昨天的日期,但数据库以 iso 格式存储日期,如:"date" : ISODate("2016-01-13T13:23:08.419Z") 所以我得到的是2016-01-13T13:23:08.419Z。我现在的问题是我不能使用昨天的变量来查询我需要的用户的数据库,即使我可以,我也不知道如何找到每个注册,不包括今天发生的那些。

有什么帮助吗?非常感谢!

【问题讨论】:

    标签: javascript node.js mongodb mongoose database


    【解决方案1】:

    您正在前端生成一个日期,然后将其推回一天,这在很多情况下都很好 -

    为此,由于您正在尝试查找发生的数据库条目,因此可以尝试使用从数据库中每个文档的 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
    

    我希望这会有所帮助!

    【讨论】:

      【解决方案2】:

      试试这个,使用Moment.js:

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

      【讨论】:

        【解决方案3】:

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

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

        这将查找在昨天结束之前创建的用户。

        momentjs 是一个超级方便的实用程序,用于进行此类操作。使用该库,这可以通过当前日期对象上的startOf() 方法来实现,将字符串'day' 作为参数传递:

        格林威治标准时间:

        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'); 
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2022-11-15
          • 2017-01-11
          • 2018-11-04
          • 1970-01-01
          • 2023-03-08
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多