So i have this collection store in mongo DB:
Exercise Records
{
username: {
type: String,
required: true
},
count: {
type: Number,
required: true
},
log: [{
description: {
type: String,
required: true
},
duration: {
type: Number,
required: true
},
date: {
type: String,
required: true
}
}]
}
This is what I do to retrieve the document based on ID:
let userExerciseData = Exercise.findOne({_id: id}});
Then, I return with res.send(userExerciseData)
.
Output:
{
"_id":"62d68cc5a586035962e18115",
"username":"paranoid_android99",
"count":3,
"log": [
{"description":"Build triceps & biceps muscle","duration":120,"date":"Tue Jul 19 2022"},
{"description":"Leg workouts","duration":30, "date":"Thu Jul 21 2022"},
{"description":"Burning calories","duration":60, "date":"Thu Jul 28 2022"},
{"description":"Plank","duration":60, "date":"Fri Jul 01 2022"}
]
}
As you can see, I'm trying to get all documents BUT WHERE the log
is only contain object WHERE the date is from Fri Jul 01 2022
to Thu Jul 21 2022
. Which will not include {"description":"Burning calories","duration":60, "date":"Thu Jul 28 2022"}
And this is what I'm trying to do:
const from = new Date('2022-07-01').toDateString();
const to = new Date('2022-07-21').toDateString();
let exerciseDataByLogs = await Exercise.findOne({
log: {
$elemMatch: {
// This doesn't work
date: {$gt: from, $lt: to}
}
}
})
console.log(exerciseDataByLogs); // return NULL
res.send(exerciseDataByLogs); // return NULL
But somehow it's always return NULL
. So what is wrong with my code?
I hope you guys understand. Thank You.