0

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.

  • You might want to take a look at this other question about [querying `ISODate` fields in MongoDB from JavaScript](https://stackoverflow.com/q/20561381/656011). – Eric Allen Jul 19 '22 at 14:38
  • @EricAllen I still can't understand. I'm very new in this. I need explanation. Like what is wrong with my code – Kevinkun Official Jul 19 '22 at 14:42
  • You should **never** store date values as strings, it's a design flaw. Store always proper `Date` objects. Then the query is simply `from = new Date('2022-07-01')` – Wernfried Domscheit Jul 19 '22 at 20:01

0 Answers0