【问题标题】:Exception in template helper: ReferenceError: collection is not defined with publish/subscribe in place模板帮助程序中的异常:ReferenceError:集合未定义发布/订阅到位
【发布时间】:2020-07-21 01:28:31
【问题描述】:

我阅读了类似的问题,但找不到与发布/订阅匹配的问题。

浏览器无法看到集合 contactsCol,为什么以及如何修复它?谢谢

// imports/api/contacts.js
import {Mongo} from 'meteor/mongo';

export const ContactsCol = new Mongo.Collection('contactsCol');


///server/publication.js

import {ContactsCol}        from '../imports/api/contacts.js';

Meteor.publish('contactsCol', function () {
  if (!this.userId) return;
  if (this.userId && Meteor.users.findOne({_id:this.userId}).profile.carsInfoMenu.indexOf('a') != -1){
    console.log('contactsCol retured documents');
    return ContactsCol.find();
  }
  return;
});


// client/main.js
Template.body.onCreated(function () {
   Meteor.subscribe('contactsCol');
});

Template.input.helpers({
  'listData': function (searchFor){
      return contactsCol.find().fetch();  //<<<< this line is causing the error
  }
});

更新我的尝试无济于事:

在 main/client.js 中添加了以下内容

`import {contactsCol} from "../imports/api/contacts.js";

  Template.body.onCreated(function () {
  Meteor.subscribe('contactsCol');


Template.input.helpers({
  'listData': function (searchFor){  //17c
  return contactsCol.find().fetch();
  }
}

【问题讨论】:

    标签: javascript mongodb meteor


    【解决方案1】:

    已解决: 我从 client/main.js 中删除了订阅行

    Template.body.onCreated(function () {
      // Meteor.subscribe('contactsCol');

    将此导入语句添加到文件顶部

    import {ContactsCol} from "../imports/api/contacts.js";
    

    在我使用的辅助方法中:

    return ContactsCol.find().fetch();
    

    为什么现在没有订阅也能正常工作?我不知道。如果有人可以解释,那就太好了。谢谢

    【讨论】:

    • 您是否安装了autopublish 软件包? Meteor 项目以autopublish 开头,用于快速原型设计,它会自动将所有数据从服务器发送到客户端,用于所有集合
    【解决方案2】:

    您还需要在客户端上导入集合。现在它是一个未定义的变量。

    // client/main.js
    import { ContactsCol } from '../imports/api/contacts.js';
    Template.body.onCreated(function () {
       Meteor.subscribe('contactsCol');
    });
    
    Template.input.helpers({
      'listData': function (searchFor){
          return ContactsCol.find().fetch();  //<<<< this line is causing the error
      }
    });
    

    订阅仅将数据从服务器加载到客户端。客户端仍然需要定义集合来存储这些文档并从中访问它们。导入集合提供了这个

    编辑:错过了模块导出的大小写

    【讨论】:

    • 我已经尝试过,但无济于事。我将更新问题以反映。您的解决方案出现浏览器错误:Exception in template helper: TypeError: Cannot read property 'find' of undefined
    • 试试绝对导入路径'/imports/api/contacts';而不是相对路径吧?
    • 那行不通。请注意导出与订阅中的“C”与“c”。为什么由于订阅中没有使用导入的变量,所以希望通过导入来解决这个问题?
    • 对不起,我在复制/粘贴时错过了大写。正如我在回答中所说,订阅不会创建供您使用的集合,它只会将数据从服务器加载到该集合中。客户端上的集合是使用new Mongo.Collection 创建的,然后您使用该集合对象来获取和操作数据
    • 澄清一下,发布和订阅可以被称为任何东西,它不会改变您访问数据的方式
    猜你喜欢
    • 2013-05-26
    • 1970-01-01
    • 2023-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-08
    • 2013-01-23
    • 1970-01-01
    相关资源
    最近更新 更多