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"?