I have a mongoose model which uses the timestamps: true flag. What I am looking for now is a way, to only get the results from the database, where the date of that created_at timestamp inside the model is the current day of querying the database. What is the best way to archieve this?
I tried using find({created_at: new Date()}) but that does not give me any results even when there has been some documents inserted earlier that day.
CodePudding user response:
let obj = {}
const beginningOfDay = new Date(new Date().setUTCHours(0, 0, 0, 0)).toISOString()
const endingOfDay = new Date(new Date().setUTCHours(23, 59, 59, 999)).toISOString()
obj.createdAt = {
$gte: beginningOfDay ,
$lte: endingOfDay
}
let items = item.find(obj)
I think this is what you need, the timestamp MongoDB uses is an ISO string. with this timestamp you will find everything that falls between those 2 timestamps