Date filtering Mongoose for Exercise Tracker

Tell us what’s happening:
My date filter doesn’t do anything. I’ve tried 3 different ways and they don’t impact the result set. Not sure what I’m doing wrong.

My schema is like this:
var userSchema = new mongoose.Schema({
username: {type:String},
exercises:[
{
description: { type: String },
duration: { type: Number },
date: { type: Date}
}
]
});

User.findOne({_id:req.params._id, ‘exercises.date’: dateObj})

Also tried like this:
//.where(‘exercises’).elemMatch({‘date’:dateObj})

And like this:
//.elemMatch(‘exercises’,{‘date’:dateObj})

Your project link(s)

solution: boilerplate-project-exercisetracker - Replit

Your browser information:

User Agent is: Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Mobile Safari/537.36

Challenge: Back End Development and APIs Projects - Exercise Tracker

Link to the challenge:

It seems to be crashing before it even gets to that test.

What should happen when the payload in the request to /api/users/:_id/exercises does not include a date?

I haven’t worked on that yet, first I am just trying to get the date filtering to work before I make it a conditional.

Regarding the tests, I don’t know why the get logs call doesn’t work and I see many CORS errors. When I run it locally, it works. But when I run it and add the date query strings, my results don’t filter.

Update: I have updated the code for conditionals in case “to” and “from” aren’t included. However the object I get as a response is ignoring the date filters and only using the limit. Am I formatting the dates incorrectly somehow?

Both the where and elemMatch methods you had tried are query operators - you need to use projection operation to filter the array data. The method to use for projection in Mongoose is the select().

Within the projection, to filter array data you can use the $filter array operator.

That did not work for me. Is this the correct syntax? I still get all the results based on the limit only and date is being ignored.
User.findOne({_id:req.params._id})
.select({‘exercises’: {$filter : dateFilter}})

Also can you please point me to the mongoose documentation for $filter? I cannot find it in mongoose, only in mongoDB.

Update: I did the filtering on the array outside of the query to solve it.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.