Pages

Thursday, July 21, 2016

Learning Meteor.js [Part 38]: Update publication to only return documents created by the current user

Now that multiple users can add ingredients it would be useful to be able to filter the ingredient list to show only the ones that you added. To enable this, the publication must support a) a search term to filter the list by ingredient name, b) whether to only include documents created by the current user and c) maximum number of documents to return:
FindFromPublication.publish('ingredients', function(limit, onlyMine, nameQuery) {
    var query = {};
    var options = {
        sort: { name: 1 },
        limit: limit
    };

     if (nameQuery) {
        query['name'] = {
            $regex: nameQuery,
            $options: 'i'
        };
    }

    if (onlyMine && this.userId) {
        query['userId'] = this.userId;
    }

    return Ingredients.find(query, options);
});

Given how MongoDb's query syntax work, we can conditionally add fields to the query object and they will be treated as a logical 'AND'. Now, on the client a new ReactiveVar is created for the new argument used within an autorun function:
Template.ingredientsListPart.onCreated(function ingredientsListPartOnCreated() {
    var instance = this;

    instance.limit = new ReactiveVar(5);
    instance.query = new ReactiveVar();
    instance.onlyMine = new ReactiveVar(false);

    instance.autorun(function() {
        var limit = instance.limit.get();
        var query = instance.query.get();
        var onlyMine = instance.onlyMine.get();

        instance.subscribe('ingredients', limit, onlyMine, query);
    });
});

Finally, a checkbox is added in the UI to toggle the reactive var. Whenever the value changes the autorun function re-executes, which re-subscribes using a different value for the filter.
Template.ingredientsListPart.events({
    'click .ingredient-search-mine': function(event, template) {
        template.onlyMine.set(event.currentTarget.checked);
        template.limit.set(5);
    }
});

You can check the code up to this point by using this commit or visit the live demo.


No comments:

Post a Comment

Note: Only a member of this blog may post a comment.