Correctly using collections in a meteor package?

烈酒焚心 提交于 2019-12-21 20:34:16

问题


I am trying to create a package that uses a collection. In a normal application, the same code works fine without any issues.

collectiontest.js (Package code)

// Why do I need to set the global property manually?
var globals = this || window;

TestCol = new Meteor.Collection('test');

globals.TestCol = TestCol;

console.log('defined');

if(Meteor.isServer){
  Meteor.publish('test', function(){
    return TestCol.find();
  });

  Meteor.startup(function(){
    console.log('wtf');

    TestCol.remove({});
    TestCol.insert({test: 'a document'});
  });
};

if(Meteor.isClient){
  Meteor.subscribe('test');
};

Test passes on client and server:

Tinytest.add('example', function (test) {
  console.log('here');
  var doc = TestCol.findOne();
  test.equal(doc.test, 'a document');
  console.log(doc);
});

But if I open developer tools on the client and run:

TestCol.find().count()

The result is 0. Why? Also, why do I have to have the line globals.TestCol = TestCol; for the tests to run at all? Without that line, an error: TestCol is not defined occurs on both the server and the client.


回答1:


Objects defined in a package can be referenced in your application once you use api.export.

In your case:

api.export('TestCol',['server','client']);

Above line will expose TestCol as global variable and it will be accesible from your Application.



来源:https://stackoverflow.com/questions/25986354/correctly-using-collections-in-a-meteor-package

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!