Exercise Tracker - Exercise Log Filters

Hello,

I just finished this project and I have a question about this part of the project.

For my database, I used a unique model with the following schema:

let exerciseUserSchema = new Schema(
  {
    username: {type: String, required: true, unique: true},
    userId: String,
    log: [{
      userId: String,
      description: String,
      duration: Number,
      date: {type: Date, default: new Date()}
    }]
  }
);

When it came to displaying the log with filters, I fed {userId : userId} to the Model.find() function as search criteria, and I used the Array.filter() method on the results to apply a given filter (e.g. exercise date being later than req.query.to).

Another way to do this whole project would be to define an exerciseUser model without a log entry, and an exerciseLog entry containing information that is in the log along with the userId but not the username. That way, I could apply the filters directly as search criteria (to use the example given earlier, we would have { date: { $gt: req.query.to } } if I’m not mistaken), but I would have to query both the exerciseUser and the exerciseLog to get everything I have to display.

My question is thus the following: is there a way to keep my exerciseUser schema as is and still be able to use the Model.find() search criteria to filter the results?

While researching this question, I found out that you can write search criteria such as {“log.duration : 10”} for example but this does not filter the log entry of the exerciseUser, it filters the exerciseUser based on whether there is at least one entry in the log array having its duration equal to 10. So it does not answer my question.

Thank you.

1 Like

I know this is a bit late, but I did find this:

They describe using MongoDB’s aggregation pipeline feature, which is supported by Mongoose:
https://mongoosejs.com/docs/api.html#aggregate_Aggregate

I have not written mine yet, but plan to.