【问题标题】:MongoDB collection is not recognized on client side客户端无法识别 MongoDB 集合
【发布时间】:2017-04-28 05:17:56
【问题描述】:

我在玩 Meteor,发现它没有按预期工作。我应该在服务器端和客户端都看到集合。但是,我似乎看不到客户端的集合。

在以下示例中,当我在 Chrome 控制台中键入“Products.find({})”时,我遇到了:

VM1592:1 Uncaught ReferenceError: Products is not defined

客户端/main.html:

<body>
  {{> addProduct}}
</body>

<template name="addProduct">

  <form class="addNewProduct">
    product name:<br>
    <input type="text" name="name"><br>
    <button type="submit" value="submit">Submit</button>
  </form>
</template>

客户端/main.js:

import {Products} from "/lib/collections/products";
import './main.html';
Template.addProduct.events({

  'submit .addNewProduct'(event) {
    event.preventDefault();

    const target = event.target;
    const name = target.name.value;

    Products.insert({ name });
  },
});

lib/collection/products.js:

export const Products = new Mongo.Collection('products');

我没有删除“自动发布”。 这里真的有什么问题?

谢谢

德里克

【问题讨论】:

    标签: javascript meteor meteor-blaze


    【解决方案1】:

    我猜你使用的是 Meteor 1.3 或更高版本,所以这是有道理的,因为在这些版本中 Meteor 适应了 ES6 模块系统。因此,您的收藏无法在全球范围内访问。如果您想在客户端控制台中访问它们,我建议在client/main.js 中使用此代码:

    import { Products } from "/lib/collections/products";
    import './main.html';
    
    if (Meteor.isDevelopment) {
      window.Products = Products;
    }
    
    Template.addProduct.events({
      // ...
    });
    

    这将允许您在开发时访问客户端控制台中的 Products 集合,但不能在生产环境中访问。

    【讨论】:

    • 那么 Meteor 1.3+ 将不再支持直接访问集合了吗?
    • 并非如此,如果您在 imports 文件夹之外定义一个没有 var/let/const 的变量,则可以全局访问该变量。
    • 换句话说,如果您使用 var/let/const 或您的文件位于“imports”文件夹下,则客户端将无法访问您的集合。这是正确的>
    猜你喜欢
    • 2018-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-26
    • 2015-10-08
    • 1970-01-01
    • 2021-09-01
    相关资源
    最近更新 更多