在客户端和服务器 Meteor 之间共享 Collection

Shared Collection Between Client and Server Meteor

Meteor 的初学者。只是学习一切是如何运作的,所以请耐心等待。

在一个文件中一切正常,但在安装 iron:router 以拥有 multi-page 应用程序后,我意识到最好有单独的客户端和服务器文件。不幸的是,现在我无法在服务器和客户端之间同步 collection。我已经阅读了大量教程,但没有任何效果。

在我的 server.js 文件中:

Streams = new Meteor.Collection("streams"); 
 if (Meteor.isServer) {
  Meteor.publish('streams', function () {
  return Streams.find();
 });
}

在我的 client.js 文件中:

if(Meteor.isClient) {
   Meteor.subscribe("streams");
   Template.body.helpers = function(){
     return Streams.find();
 }
}

调试后说客户端没有定义"Streams"。这是怎么回事?如何连接 collection?

您还需要在客户端上定义Streams

if(Meteor.isClient) {
   Streams = new Meteor.Collection("streams"); 
   Meteor.subscribe("streams");
   Template.body.helpers = function(){
     return Streams.find();
   }
}

经典架构:

lib/streams.js

Streams = new Meteor.Collection("streams"); 

server/streams.js

Meteor.publish("streams", function () {
  return Streams.find();
});

client/streams.js

Meteor.subscribe("streams");

Template.body.helpers({
  streams: function(){
    return Streams.find();
  }
});

如果你使用默认的自动发布包。你只需要做

lib/streams.js

Streams = new Meteor.Collection("streams");

部分.