Imagine you are on a movie website where you can customize filters for the movies displayed to you.
Currently, these preferences are stored in the User model as a map. Here is an example of what the preferences object might look like:
preferences: {
yearFrom: "2000",
yearTo: "2020",
actors: ["Denzel Washington", "Tom Hanks", "Morgan Freeman"]
}
Before showing you the movies, a view controller first retrieves the current user:
const user = await User.findById(req.user.id);
The preferences map is then extracted from the user (initially converted into a string before being parsed into an object):
const preferencesObject = JSON.parse(JSON.stringify(user.preferences));
Now comes the question: How do you construct the query for all movies when any of the variable query operators based on the preferencesObject are empty? The current approach looks something like this:
const preferredMovies = await Movies.find({
year: { $gte: preferencesObject.yearFrom, $lte: preferencesObject.yearTo },
actor: { $in: JSON.parse(preferencesObject.actors) }
});
If the list of actors is empty, I want to include all actors, but currently, no movies will be displayed in that scenario. If yearFrom is empty, I would like to default it to 0. With potentially more preferences to be set, how can I verify if a variable operator is empty and then either ignore it or assign a default value?