Search code examples
javascriptmeteormeteor-helper

How can I get document information in two collections?


I have two collections, a collection has images of cars (Uploads), other collection has car information (Cars), colleciton car's id is the same with carid (Uploads colleciton). I need to do that to show table cars with their picture.

Here is my code:

Template.Araclar.helpers({
  manset: function() {
    getData = Cars.find({});
    return Cars.find({});
    Uploads.find({
      "carid": getData._id
    });
  }
});

<div class="row">
    {{#each manset}}
    <div>{{aracmarka}}</div>
    <div style="width:400px; height:200px;" class="col-lg-3 col-md-4 col-xs-6 thumb m-t-30">
        <a>
            <img class="img-responsive" style="height:200px;" src="{{url}}" alt="">
        </a>
    </div>
    {{/each}}
</div>

Note: {{aracmarka}} gets from Cars collection {{url}} gets from Uploads collection.


Solution

  • You can access the data context in a template helper through the this keyword, for example:

    Template.Araclar.helpers({
        cars: function() {
            return Cars.find({});
        },
        url: function() {
            var upload = Uploads.findOne({
                "carid": this._id
            });
            return upload && upload.url;
        }
    });
    

    <div class="row">
        {{#each cars}}
            <div>{{aracmarka}}</div>
            <div style="width:400px; height:200px;" class="col-lg-3 col-md-4 col-xs-6 thumb m-t-30">
                <a>
                    <img class="img-responsive" style="height:200px;" src="{{url}}" alt="" />
                </a>
            </div>
        {{/each}}
    </div>