【问题标题】:Shared Collection Between Client and Server Meteor客户端和服务器 Meteor 之间的共享集合
【发布时间】:2015-08-07 05:26:17
【问题描述】:

Meteor 初学者。只是了解一切是如何运作的,所以请多多包涵。

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

在我的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”。这是怎么回事?如何连接集合?

【问题讨论】:

    标签: javascript mongodb collections meteor client


    【解决方案1】:

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

    lib/streams.js

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

    部分。

    【讨论】:

      【解决方案2】:

      经典建筑:

      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 文件夹应该在哪里?
      • 您应该查看文档以了解文件的加载和放置:docs.meteor.com/#/full/structuringyourapp
      • 在 Meteor 应用程序的根目录下创建它,lib 下的文件总是首先加载。
      • 工作正常,但它仍然没有返回集合...它应该在我的客户端中更新为 Streams.find() 但什么都没有出现...
      • 文档还指出,lib 文件夹中的文件首先被加载,并且可供客户端和服务器使用。它还建议将与集合相关的代码放在那里。 github 上的 Discover Meteor 示例应用程序是查看结构良好的 Meteor 应用程序源代码的好地方,您将在 lib 文件夹中看到集合声明和 CRUD 所在的集合文件夹:github.com/DiscoverMeteor/Microscope/tree/master/lib
      【解决方案3】:

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

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

      【讨论】:

      • 我想这消除了错误,但 Streams.find() 部分没有返回任何内容,它不是一个空集合......
      猜你喜欢
      • 2016-05-03
      • 1970-01-01
      • 2018-04-16
      • 1970-01-01
      • 2021-03-10
      • 1970-01-01
      • 2016-12-04
      • 2020-05-16
      相关资源
      最近更新 更多