How to serve sub Mongo collection depending on variable?


#1

How to return a Mongo sub-Collection based on geolocation?
say

Products = 
[
  {
    "name": "London TV",     
    "location": "London"
  },
  {
    "name": "New York TV",     
    "location": "New York"
  },
  {
    "name": "Default TV",     
    "location": "SomeWhere"
  }
]

if (location==London) {
    //Serve location==London sub-collection as well as Default collection
       Meteor.publish('london-collection', function () {
        return Products.find({location: 'London'});
    });
} else if (location==New York) {
    //Serve location of New York sub-collection as well as Default collection
      Meteor.publish('newyork-collection', function () {
        return Products.find({location: 'New York'});
    });
}

This is like using userID, but instead using another variable like geolocation to return sub-collections of MongodB thanks

Tried:

filterCollectionBasedOnLocation: function (cLoc) {
        var future = new Future();
        if (cLoc == 'London') {
             future.return(
                   Products.find({
                       $and: [
                           {'location': 'London'},
                           {'location': 'Default'},
                       ],
                   }),
            );
        } else if (cLoc == 'Liverpool') { etc

#2

Publications are not inherently reactive, so this is usually done with a reactive subscription which causes the publication to be re-evaluated. So a subscription will look something like:

Template.doSomething.created(function() {
  this.search = new ReactiveVar('Default');
  this.autorun(() => {
    this.subscribe('getMyStuff', this.search.get());
  });
});

with an event handler to set the ReactiveVar appropriately when the user changes location. The corresponding publication then looks something like:

Meteor.publish('getMyStuff', function(city) {
  return Products.find({ location: { $in: ['Default', city] } } ); 
});

#3

Thanks Rob…both methods should be under public folder and not server folder, correct? And a Blaze template to render the subscribed ‘getMyStuff’. Thanks

EDIT, I meant the Meteor.publish. This should be under public or server folder thanks. Don’t we need .fetch() in the end?


#4

The Template stuff is client only, the publication is server.