Utilizing variable query operators solely in instances where they hold value

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?

Answer №1

To start, construct the query object using data from the preferencesObject. Next, utilize this query object when calling the find() function. Here is an example:

let query = {
  genre: { $exists: true }  // default: true
};
if (preferencesObject.genreType) query.genre.$exists = preferencesObject.genreType;
if (preferencesObject.ratingMin ) query.rating.$gte = preferencesObject.ratingMin;
if (preferencesObject.ratingMax ) query.rating.$lte = preferencesObject.ratingMax;
if (preferencesObject.languages && preferencesObject.languages.length) {
  query.language = { $in: preferencesObject.languages };
}
const suggestedMovies = await Films.find(query)...

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Steps to modify the border width upon gaining focus

I am struggling to adjust the border width when my input box is focused. Currently, it has a 1px solid border which changes to a 2px different color solid border upon focus. However, this change in border width is causing the containing div to shift by 1px ...

Error with Webdriver/FXDriver utils.js leading to Firefox unresponsive script issue

While running browser tests with Watir webdriver and FXDriver, everything seems to be functioning well except for one test that loads a lightbox containing a large amount of HTML. When this lightbox opens, Firefox displays a popup indicating that Utils.js ...

The performance of three.js PointsMaterial is sluggish when utilizing large sprites or shapes, causing a decrease in overall

Currently, I am handling a point cloud with approximately 60,000 vertices. Interestingly, when I view the cloud at a smaller scale, performance remains acceptable. However, as soon as I zoom in and larger sprites/plans/points become visible on the screen, ...

AJAX: How to handle a successful POST request?

I have been recently exploring AJAX and I can see why I hesitated to delve into this particular area of JavaScript; it appears quite intricate. Most discussions seem centered around how to SEND data via POST, with little focus on what happens once the POS ...

Dealing with TSLint errors within the node_modules directory in Angular 2

After installing the angular2-material-datepicker via NPM, it is now in my project's node_modules folder. However, I am encountering tslint errors that should not be happening. ERROR in ./~/angular2-material-datepicker/index.ts [1, 15]: ' should ...

Guide on assigning a value to a material ui select box

Currently, I am utilizing the material UI Select component for the year field in my project. What I aim to achieve is setting a default year based on the value present in the state. To populate the years, I am using an array of years. Here is the method r ...

Creating multipart/form-data with varying Content-Types for each part using JavaScript (or Angular)

Apologies for the confusion, please refer to my update below I have a requirement to link my AngularJS Project with an existing RESTful API. This API uses POST requests that involve uploading a file and submitting form data in a request. However, one of t ...

Tips for adjusting the language settings on a date picker

Is there a way to change the language from English to French when selecting a month? I believe I need to configure something in the core.module.ts. How can I achieve this? https://i.sstatic.net/Cpl08.png @NgModule({ declarations: [], imports: [ Co ...

Updating the jQuery AJAX URL dynamically based on user input in a form submission

Exploring the world of AJAX and form submission, I find myself in need of assistance. My webpage is designed to display real-time stock market data, updating fields with the latest price, change, high, low, and more. I am currently attempting to modify th ...

having difficulties retrieving the attribute value through jquery

I'm currently implementing this method on rowmouseevent. When I use $get(eventArgs.get_id()), the output is: <tr class="normal" data-value="normal" id="ctl00_ContentPlaceHolder1_UserGrid_grdusergrid_ctl00__0" style="height:30px;" /tr> How can ...

What is the preferred approach: displaying a message using a service or a directive?

I'm feeling a bit unsure. I understand that anything interacting with the DOM should be created as a directive. However, I find it more convenient to simply call my notification service to display error or success messages. This service internally cr ...

Delete a particular item from a JSON object in real-time using TypeScript/JavaScript

Upon examining the JSON data provided, it contains a node called careerLevels which includes inner child elements. input = { "careerLevelGroups": [ { "201801": 58, "201802": 74, ...

Utilizing a library across various files in Node.js

I am looking to integrate Winston for logging in my nodejs express project. Within my main file ( server.js ) I currently have the following code snippet: const winston = require('winston'); winston.level = process.env.LOG_LEVEL winston.log(&ap ...

An error occurred with Express and Passport: ['ERR_HTTP_HEADERS_SENT']

Currently, I am diving into an ebook tutorial and have encountered a roadblock in a particular piece of code. The code is designed to take a username and password in JSON format through Insomnia or Postman, and it should return a login success cookie. Howe ...

Remove image files from a directory with jQuery without relying on PHP or AJAX

Did you know that JQuery code is capable of executing unlink operations like PHP without using AJAX or a PHP file? For instance, if you wish to delete or unlink the file "aaa.jpg" located in the folder www.myproject.com/images/, you can achieve this by s ...

Sending properties of an element to a function within Angular version 4 or 5

Trying to pass attribute values of elements to a function on button click, this is my approach: <div> <ul #list> <li class="radio" *ngFor="let option of options; let j = index" id={{i}}-{{j}} #item> <label><input t ...

Exploring the Dynamics of AngularJS: Leveraging ng-repeat and ng-show

Recently, I came across this code snippet: <div class="map" ng-controller="DealerMarkerListCtrl"> <a ng-click="showdetails=!showdetails" href="#/dealer/{{marker.id}}" class="marker" style="left:{{marker.left}}px;top:{{marker.top}}px" ng-rep ...

When a legend is clicked, it should display only the selected item while hiding all other legends automatically in a chart created

I have a highchart with 10 legends. When I click on the first legend, only that legend should remain visible while the rest are automatically hidden... Below is a code snippet with two legends: $(function() { var chart = $('#container').hig ...

Enhancing PHP function speed through pre-compilation with Ajax

I am curious about compiling server side functions in PHP with Ajax, specifically when multiple asynchronous calls are made to the same server side script. Let's consider a PHP script called "msg.php": <?php function msg(){ $list1 = "hello world ...

Experiencing an issue where the canvas element fails to render on mobile Chrome browser,

I've encountered an issue with a script that draws a canvas based on the background color of an image. The image is loaded dynamically from a database using PHP. The responsive functionality works fine on mobile Safari, but not on Chrome. When the re ...