问题描述
在MongoDB集合中,我有一个Date对象,它记录事件的日期和时间.我正在尝试根据特定日期进行查询,并忽略时间,即向我显示今天的所有事件.
Within a MongoDB Collection I have a Date object that records both the date and time of an event. I am trying to query based on a specific date and to ignore the time i.e. show me all events for today.
Model.js
var EventSchema = new Schema({
eventName : String,
eventDate : Date,
eventLocation : String,
eventLocationGeo : String,
eventCreator : ObjectId
});
我的主要 app.js 正在寻找Unix时间戳格式的日期.
My main app.js is looking for the date to come across in Unix Timestamp format.
//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小时.
Most of the reference articles reference using the $gte and $lt but no where does it mention how to strip off the time so my queries end up pulling 24 hours based on the full Date AND time.
推荐答案
我建议使用moment.unix(req.params.date).startOf('day').toDate()和moment.unix(req.params.date).endOf('day').toDate()
-of/"rel =" nofollow> moment.js库,它非常有用.
I would recommend using moment.unix(req.params.date).startOf('day').toDate()
and moment.unix(req.params.date).endOf('day').toDate()
from the moment.js library, which is phenomenally useful.
仅使用ECMAScript日期,您可以执行以下操作:
With just ECMAScript Date, you can do:
var start = new Date(req.params.date);
start.setHours(0);
start.setMinutes(0);
start.setSeconds(0);
start.setMilliseconds(0);
这篇关于使用MongoDB和NodeJS查询特定日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!