如何根据今天的日期查询 MongoDB?我试过使用 Momentjs 不起作用。这是代码,非常感谢,非常感谢任何帮助。
//mongoDB data
appointmentdate:2021-05-28T03:00:00.000+00:00
appointmentdate:2021-05-26T15:00:00.194+00:00
appointmentdate:2021-05-26T15:30:00.481+00:00
//Nodejs
const appointment = await Appointment.find({appointmentdate:{$eq: moment().format('YYYY-MM-DD')}}).sort({appointmentdate: 1})
答案 0 :(得分:2)
查询日期对象时,需要与其他日期进行比较,而不是字符串(.format('...')
方法的输出)。
要查找一天中的所有项目,您需要查询一个日期范围,这可以使用 $lt
and $gte
operators 来完成。
$lt
表示“小于”,而 $gte
表示“大于或等于”。最好让范围的一侧使用“或等于”,以避免查询错过恰好位于范围开始/结束(在本例中为午夜)的项目。
定义范围的开始和结束,然后查询其中的项目。确保将 moment 对象转换为原生 JS Date 类型,以便 Mongoose 可以理解它们。
const start = moment().startOf('day').toDate()
const end = moment().startOf('day').add(1, 'day).toDate()
const appointment = await Appointment.find({
appointmentdate: {
$gte: start,
$lt: end
}}).sort({appointmentdate: 1})