Sam Henderson
Sam Henderson

Reputation: 489

Meteor client can't import collection defined in server. Trying to import collection documents

On the client, I am trying to console.log documents from a collection defined in the server.

I have server file which defines and publishes a collection to the client.

Server file: server/main.js

const Translations = new Mongo.Collection('translations');

Meteor.startup(function () {
    Meteor.publish('translationsChannel', function () {
     return Translations.find();
    });
});

module.exports = Translations;

Client file: client/main.js

I then import the Translations collection and subscribe to 'translationsChannel' in the client.

import Translations     from '../../server/main.js';
const translationsSub = Meteor.subscribe("translationsChannel");

if (translationsSub.ready()) {
  console.log('Translations: ', Translations.find().fetch());
}

Problem: client can't import Translations successfully

Why can't I import the Translations collection to the client?

Upvotes: 0

Views: 659

Answers (1)

Sam Henderson
Sam Henderson

Reputation: 489

I identified the problem.

You can't define collections in the server and export them to the client. To fix the problem:

  • I made an imports/collections.js file that defined the Translation collection and exports it.

    const Translations = new Mongo.Collection('translations');
    
    Translations.schema = new SimpleSchema({
      userId: {type: String},
      fromLanguage: {type: String},
      fromText: {type: String},
      toLanguage: {type: String},
      toText: {type: String},
    });
    
    module.exports = Translations;
    
  • I then import Translation in my server/main.js file

    import Translations from '../imports/collections.js'
    
    Meteor.startup(function () {
      Meteor.publish('translationsChannel', function () {
       return Translations.find();
      });
    })
    
  • I then import Translation in my client/main.js file

     import Translations from '../imports/collections.js';
     const translationsSub = Meteor.subscribe("translationsChannel");
    
     if (translationsSub.ready()) {
       console.log('Translations: ', Translations.find().fetch());
     }
    
  • The trick is that you need a common directory half way between the server and the client. You can import collections from the 'middle-common' folder into both the server and the client

Upvotes: 2

Related Questions