Search code examples
javascriptmeteorcollectionfs

What to `publish` when using CollectionFS with meteor


I'm trying to get the simplest example working with CollectionFS. So I started a new project

meteor create test
cd test
meteor add cfs:standard-packages
meteor add cfs:filesystem

Now I add all the code from the README.md.

In common.js (created)

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

So in server.js (created)

Images.allow({
  'insert': function () {
    // add custom authentication code here
    return true;
  },
});

In test.js (edited from one created by meteor)

  Template.hello.helpers({
    counter: function () {
      return Session.get('counter');
    },
    // -- added ---
    images: function() {
      return Images.find();
    },
  });

  // added
  Template.hello.events({
    'change .myFileInput': function(event, template) {
      var files = event.target.files;
      for (var i = 0, ln = files.length; i < ln; i++) {
        Images.insert(files[i], function (err, fileObj) {
          // Inserted new doc with ID fileObj._id, and kicked off the data upload using HTTP
        });
      }
    }
  });

In test.html (edited from one created by meteor)

  <!-- added -->
  <input type="file" class="myFileInput"/>

  <hr/>
    {{#each images}}
      <div>
        {{this.name}}: <a href="{{this.url}}" target="_blank"><img width="50" src="{{this.url}}" alt="" class="thumbnail" /></a>
      </div>
    {{/each}}

So that all works. I set an image, it gets upload, it magically appears

Then I remove autopublish

meteor remove autopublish

What do I need to publish and subscribe to to get it work again?

Things I tried

in server.js

if (Meteor.isServer) {
  Meteor.publish("images");
}

in test.js

if (Meteor.isClient) {
  Meteor.subscribe("images");
}

No luck


Solution

  • if (Meteor.isServer) {
      Meteor.publish("images", function() {
        return Images.find();
      });
    }
    

    The client code you got is correct.