Mongoose filtering by array object property value

Mongoose filtering by array object property value
0
#1

Hi,

I am currently working on my exercise tracker project and one of issues I stumbled upon was filtering exercise values by exercise dates. Within my schema, i have defined property exercises that is holding the array of objects for exercises:

var userSchema = new mongoose.Schema({username: {type: String, unique: true} ,
                                     exercises: [{description: String,
                                                   duration: Number,
                                                   date: Date}]
                                      });

So later when I filter the exercises I need to look inside the array exercises and return the objects meeting the conditions. The way I solved this was to return all exercise array of a particular user from model.findOne() searching by id and then filtering using Array.prototype.filter(). But this approach feels wrong to me because I have to load unnecessary data in memory.
Is there a way to filter out unnecessary exercise objects already during query to mongoose?

1 Like
#2

It took me a while, but I found the documentation on how to solve this issue: https://docs.mongodb.com/manual/tutorial/query-array-of-documents/#specify-a-query-condition-on-a-field-embedded-in-an-array-of-documents

You may wish to do a quick google search for the documentation on $in and $all, depending on what exactly you want to do.

Example: If you are looking for users who have done one or more exercises where the duration is up to 30 minutes you may try using:
userSchema.find( { 'exercises.duration': { $lte: 30} } );
This is assuming that duration is in minutes.

Example: If you are looking users who have done an exercise with the description of ‘jumping jacks’, then you may try using:
userSchema.find( { 'exercises.description': 'jumping jacks' } );

1 Like