Search code examples
meteorcollectionfs

Meteor: Retrieving images within collections


I'm writing to this collection:

GiftCards = new Mongo.Collection('giftcards');

GiftCards.attachSchema(new SimpleSchema({
    cardType: {
        type: String
    },
    cardValue: {
        type: Number,
        defaultValue: 100
    },
    fileId: {
        type: String,
        autoform: {
            afFieldInput: {
                type: "fileUpload",
                collection: "Images"
            }
        }
    }
}));

Images = new FS.Collection("images", {
    stores: [new FS.Store.FileSystem("images", {path: "public/uploads"})]
});

With a form made with AutoForm.

 {{> quickForm collection="GiftCards" id="giftCardsForm" type="insert"}}

Data is written, but I don't find a way to show the image associated with every document in the collection......I have only the id (in fileId) and don't find the way to publish correctly image with specific documents it refers...


Solution

  • It looks like your GiftCards collection includes a single foreign key reference to the Images collection as fileId. This is actually just like SQL in the sense that the primary key of the Images collection is used as a foreign key in GiftCards.

    Now you want to display a gift card and its related single image.

    <template name="showOneGiftCard">
      Type: {{type}}, value: {{value}} <img src={{url}}/>
    </template>
    

    Then you need a helper to return the url of the image:

    Template.showOneGiftCard.helpers({
      url: function(){
        var img = Images.findOne(this.fileId); // 'this' is the data context of one GiftCard
        return img && img.url(); // will return undefined if there's no attached image
      }
    });