Search code examples
meteormeteor-blaze

Display profile picture based on ID


  1. Users register and all data is in the collection "users" (meteor useraccounts).
  2. In the profile page a user can upload a profile picture (meteor-files). The picture metadata is registered in the collection 'images'.

Everyone is allowed to browse the profiles and it works very well except i need to dynamically change the src link for the profile picture on each card displaying. I'm not sure how to go about this when the information i need is in another collection.

images collection:

{
    "_id" : "LT6aCTFkbRn6AAKBg",
    "size" : 1467914,
    "type" : "image/jpeg",
    "name" : "profil.jpg",
    "meta" : {},
    "ext" : "jpg",
    "extension" : "jpg",
    "extensionWithDot" : ".jpg",
    "mime" : "image/jpeg",
    "mime-type" : "image/jpeg",
    "userId" : "3JAt887HkSooRRPk2",
    "path" : "assets\\app\\uploads\\images\\LT6aCTFkbRn6AAKBg.jpg",
    "versions" : {
        "original" : {
            "path" : "assets\\app\\uploads\\images\\LT6aCTFkbRn6AAKBg.jpg",
            "size" : 1467914,
            "type" : "image/jpeg",
            "extension" : "jpg"
        }
    },
    "_downloadRoute" : "/cdn/storage",
    "_collectionName" : "images",
    "isVideo" : false,
    "isAudio" : false,
    "isImage" : true,
    "isText" : false,
    "isJSON" : false,
    "isPDF" : false,
    "_storagePath" : "assets\\app\\uploads\\images",
    "public" : false
}

The _id (LT6aCTFkbRn6AAKBg) is not the userId.

Template.profileDetails.helpers({
   user: function() {
    return Meteor.users.find();
  },

  PSEUDO:
  imageLinkForThisUser: function() {
    return Images.find('document in collection which has same userId key in it and return path');
  },

Thank you!


Solution

  • Meteor.userId() will return the current _id of the user if he is logged in.

    So your mongo query should be:

    Images.findOne({userId: Meteor.userId()})['path'];
    

    You can use findOne instead of find as (I assume) that there will be only one image per user stored.

    Your helper function will be:

    Template.profileDetails.helpers({
       ...
       imageLinkForThisUser: function() {
        return Images.findOne({userId: Meteor.userId()})['path'];
      },
      ...
    });
    

    HTML:

    <img src={{imageLinkForThisUser}} />
    

    Side tip: You don't need to have a helper that returns the userid / user data. You may directly use handlebars to retrieve the same.

    Eg. {{currentUser.username}}
    

    More on that in this answer