Search code examples
mongodbmeteorcollectionspublishpublish-subscribe

Cannot publish a MongoDB collection from the server to client Meteor


I want to publish a sever side collection to the client side.

In Server Side

MedicalCenters = new Mongo.Collection('medicalCenters');

Meteor.publish('medicalCenters',function () {
    return MedicalCenters.find({});
});

I want this collection only to be accessed by a particular template. Thefore,

In Client Side

Template.doctor.onCreated(function () {
    Meteor.subscribe('medicalCenters');
});

Now I can pass the data from client side template and even write to the serve side collection. But it seems to be subscription did not work and therefore, I cannot display collection data in the template. (The collection is not displayed in the meteortoys Mongol)

How do I fix this?


Solution

  • It sounds like you have not placed your collection definition code in a common location that is executed by both the client and server. I'm making this assumption because you said that the collection itself was not visible in mongol.

    Remember that in order for publish/subscribe to work, collections must exist on both the client side (using minimongo) and the server side (using mongodb).

    Refer to the Meteor Application Structure guide for the details, but essentially you should put your collection definition code in a file that is not within a special directory (e.g. the server/ or client/ folder). Doing so ensures that the code is executed by both the client and server (per the meteor api docs).

    All JavaScript files outside special directories are loaded on both the client and the server.

    In the older meteor days (before we had the imports/ folder) people often placed their collection definition code inside a lib/ folder within the meteor project root. Now it's common for it to be within the import/api/ directory as described here.