Search code examples
javascriptmongodbmeteoriron-router

Meteor find not returning data


My collection is created in collections.js

portfolioCategories = new Mongo.Collection('portfoliocategories');

It is then subscribed to in subscriptions.js

Meteor.subscribe('portfoliocategories');

And published in publications.js

Meteor.publish('portfoliocategories',function(){
    return portfolioCategories.find();
});

If I query Mongo from the server with db.portfoliocategories.find() I'll get

{ "_id" : "W9AeauCpMgPw2j5hf", "title" : "Commercial Design", "slug" : "commercial-design", "image" : "https://url/9c3ba46d-c09a-4a7d-ac40-5752fc24ad2c.jpg" }

From the client and ironrouter both, however, find returns nothing. For example if I type into the console:

portfolioCategories.find({'_id':'W9AeauCpMgPw2j5hf'});

I will get a LocalCollection.Cursor with undefined key values:

_selectorId: undefined

_transform: null

collection: LocalCollection

fields: undefined

limit: undefined

The same thing happens in iron-router if I try to return that as data. Yet, if I use findOne I'll get the document.

portfolioCategories.findOne({'_id':'W9AeauCpMgPw2j5hf'})

Object { "_id" : "W9AeauCpMgPw2j5hf", "title" : "Commercial Design", "slug" : "commercial-design", "image" : "https://url/9c3ba46d-c09a-4a7d-ac40-5752fc24ad2c.jpg" }

My issue is that I need to return all items with the the same title. Because of this, findOne() is not a proper solution.

What am I missing?


Solution

  • The confusion came because of the differences between iron-router's data object. What I was trying to do from iron-router was

    waitOn:function(){
    
        return [Meteor.subscribe('projectsportfolio'),Meteor.subscribe('portfoliocategories')];
    
    }
    data:function(){
        currentSlug = this.params.category;
        currentCategory = projectsPortfolio.find({slug:currentSlug});
        if(typeof currentCategory != 'undefined'){
            return currentCategory
        }
    }
    

    But this only returns a cursor as @David Weldon explained. The solution is:

    data:function(){
        currentSlug = this.params.category;
        currentCategory = projectsPortfolio.find({slug:currentSlug}).fetch();
        if(typeof currentCategory != 'undefined'){
            return currentCategory
        }
    }
    

    currentCategory will now be an array of objects that I can now loop through in my template as

    {{#each currentCategory}}
        {{keyvalue}}
    {{/each}}