Exploring various characteristics in MongoDB using Meteor

After successfully implementing a publish method in Meteor that runs a query to my mongo collection through a given attribute when subscribing in the template.js, I now want to expand this functionality by adding a multiple attribute search. Imagine a scenario where I have a Mongo collection with documents sharing the same attributes but with different values.

{batch:'HAHT020614' color: 'blue', material: 'plastic', printing: true, 
  model: 'H100', handle: 'plastic', product: 'C010' }
{batch:'HBTH060614' color: 'red', material: 'metal', printing: false, 
  model: 'V400', handle: 'metal', product: 'P001' }
...

To achieve this, I am attempting to pass an object to the publish method containing all user-selected fields through reactive vars:

Template.inventory.onCreated( function appBodyOnCreated() {
    this.searchQuery = new ReactiveVar({
        color: anyItem,
        batch: anyItem,
        model: anyItem,
        material: anyItem,
        handle: anyItem,
        printing: anyItem,
        product: anyItem,
    });
    this.autorun(function () {
        let template = Template.instance();
        template.subscribe("stock.search", template.searchQuery.get());
    });
});

Subsequently, in publication.js:

Meteor.publish('stock.search', function stockQuery(search) {
  return Stock.find(
    { $and: [
      {color: { $regex : search.color }},
      {batch: { $regex : search.batch}},
      {product: { $regex : search.product}},
      {model: { $regex : search.model}},
      {material: { $regex : search.material}},
      {handle: { $regex : search.handle}},
      {printing: { $regex : search.printing}}
      ]
    }, 
    { limit: 10, sort: { batch: 1 } });
});

The challenge lies in the fact that some search fields may or may not be utilized in the application based on the user's requirements. The goal is to enable the search for items that are, for instance, both blue and made of metal, allowing users to mix and match criteria as needed.

While the object successfully reaches the publish method and attribute extraction is successful, the issue arises in the query itself. I am unsure if it's feasible to instruct Mongo to match specific attributes to "any". Attempting to use { $exists: true } as a default attribute (when the search field is empty) to match any document in the collection did not yield the desired results. In this case, I am employing regex for "contains" functionality while anyItem is simply an empty string.

Is there a recommended method to query Mongo to match only certain attributes to chosen values while leaving others as "any"?

Answer №1

One approach is to pass only the non-null criteria to the publish method and construct a query using those criteria. Here's an example:

Meteor.publish('stock.search', function stockQuery(search) {
   const criteria = Object.keys(search).map(k => ({ [k]: { $regex: search[k] } }));
   return Stock.find(
       { $and: criteria }, 
       { limit: 10, sort: { batch: 1 } }
   );
});

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

Interval set does not refresh an integer

I'm struggling with a function that is supposed to show the number of milliseconds elapsed since Midnight on January 1st, 1970. I've been trying to use setInterval to update the integer every second or millisecond, but it doesn't seem to be ...

AngularJS: Advanced Routing for Dynamic Web Applications

Hello, I am currently exploring the possibility of implementing something similar to this code snippet using AngularJS: $routeProvider .when('/root/:controllerName/blah/:blahId/blah/:blah', { templateUrl: '/tmpl/:controllerName ...

Challenge with Sequelize Many-to-Many Query

Currently, I am facing an issue with connecting to an existing MySQL database using Sequelize in Node. The database consists of a products table, a categories table, and a categories_products table. My goal is to fetch products, where each product includes ...

What is the best way to interact with a checkbox that has a label using Selenium in Node.js?

My HTML document contains multiple checkbox classes with different texts for each checkbox name. Here is a snippet of the HTML code: <div class="col-md-12 syllabus-div-1"> <h4 class="vertical-spacing">Coaching<i class="fa fa-graduation- ...

Limiting click event to only Image component in Next.js

Is there a way to trigger a click event only on the image itself, rather than the entire parent div? When setting width and height for the parent div, the click event seems to encompass the entire area. For instance, if the image is 600 pixels wide by 300 ...

Use JavaScript executor in Selenium WebDriver to interact with list items by clicking on them

I am facing a challenge where I need to gather multiple links, click on each link, and extract specific information from the website to export into Excel. My approach involves collecting all the links in one list and attempting to click on each one based ...

Is there a way for me to retrieve the variables saved within this array in JavaScript (vue.js)?

I'm currently working on a project involving the JavaScript Vue.js Framework. I've encountered an issue that I need help with, and I've included some code below to illustrate my problem. In the code, I have two variables in the data section ...

How can we use fetch to grab some data?

I put together an Express application quickly, here's how it looks: const express = require("express"); const app = express(); const port = 3000; app.get("/content/1/", (req, res) => res.send("Thinking about taking out a new loan? Call us today. ...

Here is a guide on how to specify function selection values for a total order. By default, the selection will have predetermined values, and upon clicking the sum button,

<tr id=""> <th> <select id="selection" onchange="myFunction()"> <option id="0" value="0">None</option> <option id="1" value="4.00">Women Suit</option> <option id="2" value="10.00">Dres ...

Automatically omitting a selector that mimics a switch

After conducting thorough research, I discovered a variety of solutions using jQuery and Vanilla. While one answer perfectly addressed my issue, it failed to integrate effectively with the rest of my code. So, I decided to modify the code from this Stack O ...

What is the process for invoking a websocket from an HTML client?

I have created a WCF Service using netHttpBinding binding and it is hosted on IIS 8 (Windows Server 2012). The interfaces for the service are as follows: [ServiceContract(CallbackContract = typeof(IDuplexCallbackContract))] public interface IHelloWebSocke ...

Encountered an error message stating "This dependency was not found" after installing a package using npm

I recently added a package called htmldiff to my Vue project using the npm install command. The next step was to try importing the package into one of my components. import { diff } from 'htmldiff'; // note that the package does not use default ...

Server Components can only receive plain objects and select built-ins from Client Components. Any classes or null prototypes will not be compatible

I am encountering an error when wrapping the App.ts with queryclientprovider: "Only plain objects, and a few built-ins, can be passed to Client Components from Server Components. Classes or null prototypes are not supported." Below is the code snippet from ...

Error: Property cannot be read after page refresh or modification

Upon refreshing or running the project for the first time, I encounter the error: TypeError: Cannot read property 'statements' of undefined This issue is perplexing as the data renders correctly but it appears that the connection is failing. ...

Refresh the page to change the section using vue.js

I am currently working on a website using Laravel and Vue.js. I require two separate sections for the site: Site: https://www.example.com Admin: https://www.example.com/admin Within the resource/js/app.js file, I have included the main components as fo ...

I am encountering problems with images that are imported as module imports in a Vue.js project

Currently, I have stored all the default images for my Vue project in a designated folder. The path to this folder is web/images/defaults/<imageNames>.png. Instead of importing each image individually in my components, I wish to create a file that co ...

Utilizing Aramex API in React Native: A Step-by-Step Guide

Currently, I am tackling an eCommerce venture that requires the utilization of Aramex APIs for shipping and other functionalities. Since my project is being developed in React Native, I am seeking guidance on how to integrate Aramex APIs into this framewo ...

Exploring the world of cookies and sessions in Node.js

After setting up an API server using Node.js and a client side using React.js, the client runs on url:5000 and the server runs on url:3000 separately. The client side sends requests to the server side and receives responses. When a user logs in, a session ...

Trouble obtaining output from chrome.tabs in browser console

Currently, I am experimenting with the browser's console and attempting to retrieve all the details of the active tabs. In order to do so, I open the browser's console and input the following: However, I encountered the following error: VM713:1 ...

Having trouble retrieving textfield value with jQuery

On my website, I have an invoice.jsp page that requires jQuery to calculate values in textboxes. Within the invoice, there is a quantity textbox. When a user enters a quantity, the price should be dynamically calculated as (total_subPrice= unit_price * qu ...