I am trying to find all documents that are created greater than or equal to a month ago.
But when I query the DB it returns nothing when doing the following code:
console.log(moment().add(-31, "days").toDate()) // this logs 2022-09-30T07:27:26.373Z
let filter = {
companyId: companyId,
userId: userId,
_created_at: {$gte: moment().add(-31, "days").toDate()}
};
db.collection("Users")
.find(filter)
.count()
.then(count => {
if(!count){
return resolve({result: [], count: 0});
} else {
db.collection("Users")
.find(filter)
.sort({_created_at: -1})
.limit(parseInt(limit))
.skip(parseInt(page) * parseInt(limit))
.toArray()
.then(result => {
resolve({result: result, count: count});
})
.catch(error => {
console.log(error);
reject(error);
})
}
});
However when I do the following filter it works and returns the documents:
let filter = {
companyId: companyId,
userId: userId,
_created_at: {$gte: moment().add(-31, "days").format("YYYY-MM-DD[T]HH:mm:ss.SSS[Z]") }
};
The only thing i changed is the format of the date and i am specifiying exactly how it should be formatted to equal the DB but i do not want to do something hard coded. Although the moment().add(-31, "days").toDate() matches the same format in my DB.
Why am i not getting any results from the query?
CodePudding user response:
[toDate()][1]
returns a JS Date object, try with format()
to return an ISO formatted date:
let filter = {
companyId: companyId,
userId: userId,
_created_at: { $gte: moment().add(-31, 'days').format() },
};