What is the best way to filter out empty arrays when executing a multiple get request in MongoDB containing a mix of strings and numbers?

I am currently working on a solution that involves the following code:

export const ProductsByFilter = async (req, res) => {

  const {a, b, c} = req.query

  let query = {}

  if (a) {
    query.a = a;
  }
  if (b) {
    query.b = b;
  }
  if (c) {
    query.c = c;
  }

  const products = await Product.find(query);

  res.status(200).json(products);
}

The challenge I'm facing is that a is a String and b is a Number, so they work fine when making multiple requests even if one is empty. However, c is an array and it's not functioning properly. How can I adjust the logic to make c work as well, while still allowing for multiple query requests that ignore empty or null parameters?

Answer №1

After receiving a user's code as a response, I made some modifications to ensure its full functionality. The addition of $in in the code snippet below allowed me to successfully execute the query with an array:

    export const ProductsByFilter = async (req, res) => {

    const {a, b, c} = req.query

    let query = {}

    if (a) {
       query.a = a;
    }
    if (b) {
       query.b = b;
    }
    if (c?.length) {
       query.c ={$in:c};
    }

    const products = await Product.find(query);

    res.status(200).json(products);
                                                          }
         

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

Displaying JSON array data across three different pages using AngularJS and Ionic framework

I have an array of categories with multiple products. I want to display these categories on a category page. When a category is clicked, it should redirect to the product page and show the relevant products. Similarly, when a product is clicked, it shou ...

The Angular framework may have trouble detecting changes made from global window functions

While working, I came across a very peculiar behavior. Here is the link to a similar issue: stackblitz In the index.html file, I triggered a click event. function createClause(event) { Office.context.document.getSelectedDataAsync( Office.Coerci ...

What is the reason behind having all bindings resolved during each $digest cycle?

Upon placing a breakpoint on a bound function, I discovered that it is being triggered every cycle. This came as a surprise to me as the timer displaying a countdown on the page was updating other properties as well. The demonstration below showcases thre ...

automatically changing radio button selection based on dropdown choice

Let's address the issue at hand: I have a dropdown list with over three options, and alongside it, a radio group for yes or no responses. What I am aiming to achieve is setting the radio button to "no" when option 1 is selected, and to "yes" when any ...

Issues encountered when attempting to append the array objects to HTML using $.getjson

Hello, I have a JSON data structure as shown below: [{ "menu": "File", }, { "menu": "File1", }] I have created jQuery code to dynamically add the response to my HTML page like this: $(document).ready(function () { $.getJSON('data.json&a ...

Using useState in ReactJS does not allow setting state data

I am working with a react component that handles agreements. import React from "react"; import { AgreementInfo } from "../../../../models/shop"; import { MdClose } from "react-icons/md"; import moment from "moment"; ...

Validation of textfields using React.js

Currently, I am working on implementing a validation feature in ReactJS. Specifically, I have a field named "name" and my requirement is that every time a name is entered, it must be equal to or greater than 2 characters. The validation works fine when t ...

Optimal approach for integrating enum with Angular, Mongoose, and Node.js

When it comes to fetching values from MongoDB and displaying them with AngularJS, the process can be straightforward with Jade but becomes more complex with Angular. Here is how the data flows: An array of items is retrieved from MongoDB, each containin ...

Creating an empty array within an object in JavaScript

Consider the following scenario: var form = { header: { value: null, isValid: false, type: 'textinput', rules: { isRequired: true, ...

Explore the capabilities of Vue.js by creating multiple JavaScript classes within your application

<div class="container" :class="{ qwerty: !open }" :class="lower? 'left' : 'right'"> Hey there, I've noticed that Vue seems to only allow me to add one class with conditions, as shown in the exam ...

I'm looking to dive into the world of MongoDB and NoSQL databases and need a

Utilizing PHP, mySQL, and CodeIgniter extensively, I am accustomed to writing SQL statements to manage and manipulate data. However, I find this process to be quite archaic, and I have been intrigued by the positive feedback surrounding MongoDB, a schema-l ...

Struggling to display my array data retrieved from the database on my Angular 5 page

I hope everyone is doing well. I am currently facing a problem with retrieving data from Firebase. I have an array within an array and I want to display it in my view, but I am encountering difficulties. Let me share my code and explain what I am trying to ...

I encountered the following error message: Unable to access properties of undefined (specifically 'header'). I am currently attempting to utilize middleware to retrieve user data

I recently set up a middleware folder and created fetchuser.js within it. The purpose of my fetchuser.js code is to create a getuser endpoint for user authentication. However, I encountered an error while trying to make a new post request using thunderclie ...

Tips for detecting a new day with server-side JavaScript

I am currently developing a website that includes a schedule for teachers. I have encountered the need to delete elapsed days data from a database. What is the most effective method to monitor when it is exactly 12 midnight? If I were to use setInterval( ...

Posting several pictures with Protractor

In my test suite, I have a specific scenario that requires the following steps: Click on a button. Upload an image from a specified directory. Wait for 15 seconds Repeat Steps 1-3 for all images in the specified directory. I need to figure out how to up ...

Using JavaScript, what is the process for getting the value of a child node within Firebase

var ref = firebase.database().ref("games/" + gameId + "/patterns"); ref.on("child_changed", function(snapshot){ var pattern = snapshot.key; console.log(pattern); }); Currently, the code snippet above only logs the key. But how can I extract the player ...

Can you define a secondary index in MongoDB and review the execution plan when using an update statement?

Currently, my MongoDB instance is running on Ubuntu. I understand that it's not possible to utilize the .hint() or .explain() methods with an update command to achieve the following: 1) Specify an Index to be used in the query part of the command, a ...

How can I send dynamic props between pages using Next.js?

I am currently exploring Next.js and attempting to create a page (index.js) that fetches data about different countries and then displays this information. I would like each country element displayed on the page to have a button that leads to another page ...

Implementing Gatsby-js for client-side JavaScript directly within a blog post is a powerful

I've been working on setting up a blog using Gatsby-JS and have run into a bit of an issue. My posts, written in markdown, include inline javascript like this: <script>window.alert("hello");</script> When I test the site with "Gatsby ser ...

Aframe Descend Rotation

I am currently working on a project in Aframe and I'm looking to implement a control/event that enables an entity to rotate downward. While attempting to create a new animation and add it as a child object to the entity, I have achieved successful re ...