javascript - 如何修复meteor.js中的 "Exception in template helper: ReferenceError: Todos is not defined"错误

标签 javascript mongodb templates meteor referenceerror

我在 Udemy 开始了全栈开发类(class),其中有一个 Meteor 部分。当我编译代码时,出现以下错误:“模板助手中出现异常:ReferenceError:Todos 未定义”。

我尝试在 stackoverflow 中搜索解决方案,但似乎都不起作用。

我尝试用“body”命名模板,这是建议之一。

这是我得到的。

客户端/main.js

import { Template } from 'meteor/templating';
import { Todos } from '/lib/collections';
import './main.html';

Template.main.helpers({
  title(){
    return 'QuickTodos';
  },
  todos(){
    const todos = Todos.find();
    return todos;
  }
});

Template.main.events({
  'submit .add-todo'(event){
    event.preventDefault();

    const text = event.target.text.value;
    const time = event.target.time.value;

    Todos.insert({
      text,
      time
    });

    event.target.text.value = '';
    event.target.time.value = '';
  }
});

Template.todo.events({
  'click .toggle-checked'(event){
    Todos.update(this._id, {
      $set:{checked: !this.checked}
    });
  },
  'click .delete'(event){
    Todos.remove(this._id);
  }
});

客户端/main.html

<head>
  <title>QuickTodos</title>
</head>

<body>
  {{> main}}
</body>

<template name="main">
  <header>
    <h1>{{title}}</h1>
    <form class="add-todo">
      <input type="text" name="text" placeholder="Add Todo...">
      <input type="text" name="time" placeholder="Add Time...">
      <button type="submit">Add</button>
    </form>
  </header>
  <ul>
    {{#each todos}}
      {{> todo}}
    {{/each}}
  </ul>
</template>

<template name="todo">
  <li class="{{#if checked}}checked{{/if}}">
    <button class="delete">&times;</button>
    <input type="checkbox" checked={{checked}} class="toggle-checked">
    <strong>{{time}}:</strong> {{text}}
  </li>
</template>

lib/collections.js

import { Mongo } from 'meteor/mongo';

export const Todos = new Mongo.Collection('todos');

当我现在编译时没有错误,但是当我在浏览器控制台中搜索时 Todos.find().fetch() 它给出了这个错误:

Uncaught ReferenceError: Todos is not defined
    at <anonymous>:1:1

最佳答案

您需要从collection.js中导出Todos并将其导入到client/main.js文件中 //在你的 lib/collection 文件中执行此操作

import { Mongo } from "meteor/mongo";
const Todos = new Mongo.Collection("todos");
export default Todos;

在 main/server.js 文件中,您需要导入 Todos

import Todos from "../lib/collections";

同时在 client/main.js 文件中导入 Todos

import Todos from "../lib/collections";

完成上述操作后,待办事项将可见。干杯

关于javascript - 如何修复meteor.js中的 "Exception in template helper: ReferenceError: Todos is not defined"错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57379039/

相关文章:

javascript - 这段代码有什么作用? "data.target == this"

node.js - 从node.js中的mongoDB数据生成JSON树

javascript - 如何在mongo和javascript中控制一个集合字段中的多个更新?

javascript - 如何在 MongoDB 对象的每个嵌套数组中添加额外的元素?

c++ - 错误 'TempSLLNODE' : use of class template requires template argument list

javascript - 如何在像 Angular 这样的 javascript MVC 框架上隐藏数据库凭据

javascript - 如何在 IE 中查看 JavaScript/JQuery 代码的错误消息?

javascript删除行匹配模式

css - Django 模板 : Group items in Threes

c++ - 检查模板参数