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

Sending various data from dialog box in Angular 8

I have implemented a Material Design dialog using Angular. The initial example had only one field connected to a single parameter in the parent view. I am now trying to create a more complex dialog that collects multiple parameters and sends them back to t ...

Using JS regular expressions to only select anchor (a) tags with specific attributes

When trying to select a link tag (a) with a specific data-attr, I encountered an issue. I currently use the following regex pattern: /<a.*?data-extra-url=".*?<\/a>/g. However, I noticed that this selection goes wrong when there are no line br ...

When I try to post using the raw feature in Postman in Node.js, the post ends up empty

My API is supposed to receive data for saving in the database. However, when I call the PUT method, my req.body.nome returns empty. It works fine with form-urlencoded, but I've tried using body-parser and it's deprecated. Here is my request usin ...

Issues with passing Angular directive attributes to the scope were encountered

I am having an issue with my angular directives where the arguments are not being passed into the scope: app.directive('sectionLeft', function() { return { restrict:'E', scope: { sectionContent: '=', s ...

Obtaining the NodeValue from an input of type <td>

I have a HTML code snippet that I am trying to parse in order to extract the nodeValue of all elements within the table columns. <table id="custinfo"> <tr> <td><label>First Name</label></td> <td& ...

Display all pages in the DataTables plugin while utilizing responsive tables and additional features

I am struggling to combine the responsive and fixed header attributes of my current function with the "Show All" list feature, similar to what is demonstrated in this example: https://datatables.net/examples/advanced_init/length_menu.html I need assistanc ...

Troubleshooting Autocomplete User Interface Problems

I am currently working on a website user interface and I have encountered an issue specifically in IE7. When searching for a company, the display is not showing up correctly, as demonstrated in the image below. This problem only occurs in IE7, it works fi ...

Utilizing Inquiries within Arrays

I've been working on a quiz application and I have successfully built the array with questions and answers. However, I'm facing some challenges in getting the next question to display after clicking the submit button. Here is a snippet of the cod ...

The CSS property overflow:hidden or overflow:scroll is not functioning as expected when applied to a

On my practice website, I have set up a demonstration for showcasing text data. The issue arises when the user inserts an excessive amount of characters in the text box. To address this, I would like the text to be scrollable so that all content can be d ...

Various tasks to be executed on a shared element

Struggling with implementing actions on a grid component without using a router in Next.js. Here is the current code snippet: const handleActions = (btnPress, row) => { if (btnPress === "Add") {/* implementation */} else if (btnPr ...

Setting a background image in vanilla-extract/css is a straightforward process that can instantly enhance

I am brand new to using vanilla-extract/CSS and I have a rather straightforward question. I am attempting to apply a background image to the body of my HTML using vanilla-extract, but I am encountering issues as I keep getting a "failed to compile" error. ...

Getting the most out of your weather API: optimizing search parameters for precise location results and avoiding any confusion with similar locations

When experimenting with new platforms, I often utilize the openweathermap.org's api. However, I have encountered a recurring issue where I struggle to define a precise query for finding certain cities. The api functions smoothly for major cities like ...

Error Encountered - Node.js application experiencing issues in passport login functionality

I'm in the process of developing a login application using nodejs and incorporating passport js for authentication. The app is connected to a local MySql database and utilizes sequelize as its ORM library. Within my user model, I've implemented ...

Show PHP results in an Ajax modal box

Hey everyone! I'm new to this and had some code written for me by a programmer. Unfortunately, I can't reach out to them for help anymore. I have a calculator that shows results (generated by calc.php) without refreshing the page. Check out the ...

Manipulating a 2D array in Javascript and Jquery: Implementing push functionality

I am trying to set up an array structure as follows: track[divID][wrapID] However, when I attempted track[divID][wrapID] = wrapID, I encountered an issue. This is because I need to add more elements to the second dimension in another loop, like this: tr ...

Each keystroke is saved individually in an array, thanks to React, instead of storing the entire text

Hey everyone, I have a task to develop a full-stack web application that allows users to create meals with ingredients, preparation details, and cooking time. I am using MongoDB, Node.js, Express, and React for this project. Everything works fine when test ...

Is the Jest function, containing an asynchronous call to User.findAll [using Sequelize with PostgreSQL], failing its test?

Why is my test failing for the getAllUsers function? I suspect that the assertions are executed before all async calls to User.findAll complete. Any suggestions on how to fix this? Here is the code being tested: const { Op } = require('sequelize&apo ...

Facing challenges in both client-side and server-side components

import axios from 'axios'; import Image from 'next/image'; export const fetchMetadata = async({params}) => { try { const result = await axios(api url); return { title: title, description: Description, } / } catch (error) { con ...

Struggling with implementing the use of XMLHttpRequest to transfer a blob data from MySQL to JavaScript

I have a blob stored in my local WAMP64/MySQL server that I need to retrieve and pass to an HTML file using XMLHttpRequest. I know I should set responseType="blob", but I'm not sure how to transfer the blob from PHP to JavaScript in my HTML file. Any ...

Why is there a delay in processing queries and requests in the MEAN Stack?

Recently, I've been diving into Node.js and experimenting with building a web app using the MEAN stack. One particular issue I encountered involved sending an array of strings (e.g., ["one", "two", "three"]) to the server side. In response, I attempt ...