【问题标题】:Query for a specific date with MongoDB and NodeJS使用 MongoDB 和 NodeJS 查询特定日期
【发布时间】:2014-09-15 18:19:49
【问题描述】:

在 MongoDB 集合中,我有一个 Date 对象,它记录事件的日期和时间。我正在尝试根据特定日期进行查询并忽略时间,即显示今天的所有事件。

Model.js

var EventSchema = new Schema({
eventName        : String,
eventDate        : Date, 
eventLocation    : String,
eventLocationGeo : String,
eventCreator     : ObjectId
});

我的主要 app.js 正在寻找 Unix Timestamp 格式的日期。

//Get Events based on Unix Time Stamp Date
app.get('/events/date/:date', passportConf.isAuthenticated, function(req, res){
var user = req.user._id;
var date = req.params.date;
console.log('date - ' + date);
eventController.getEventsByDate(user, date, req, res);
});

典型的 REST 调用

    http://localhost/events/date/1410764400

大多数参考文章都使用 $gte 和 $lt 进行引用,但没有提到如何去除时间,因此我的查询最终会根据完整的日期和时间拉 24 小时。

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    我建议使用moment.js library 中的moment.unix(req.params.date).startOf('day').toDate()moment.unix(req.params.date).endOf('day').toDate(),这非常有用。

    仅使用 ECMAScript 日期,您可以:

    var start = new Date(req.params.date);
    start.setHours(0);
    start.setMinutes(0);
    start.setSeconds(0);
    start.setMilliseconds(0);
    

    【讨论】:

      猜你喜欢
      • 2014-02-12
      • 1970-01-01
      • 1970-01-01
      • 2012-08-11
      • 2021-01-03
      • 1970-01-01
      • 1970-01-01
      • 2013-09-25
      相关资源
      最近更新 更多