Meteor 1.4,如何访问包中的用户定义集合

时间:2016-11-07 01:16:56

标签: javascript meteor package

背景

所以我正在为meteor 1.4.2创建一个管理包,并做出反应,这样我就可以学习如何做到这一点。管理包将只能更新用户定义的集合(插入,删除,修改)。

我在imports/api/posts.js下的应用程序中有这个文件:

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

export const Posts = new Mongo.Collection('posts');

if (Meteor.isServer) {
   Meteor.publish('posts', function postsPublication() {
      return Posts.find();
   });
}

我可以使用例如import { Posts } from '../imports/api/posts.js';轻松访问我的应用程序中的此文件。

问题:

如何从管理包中访问相同的Posts集合,以便插入新项目,删除项目等?

另外,我之前看到this post类似的事情,但这是否意味着诸如yogiben:admin之类的软件包也无法与模块系统一起使用?

2 个答案:

答案 0 :(得分:3)

理解这一点的关键是要意识到一些流星包是库,有些是(Meteor)框架的扩展defined here

yogiben:admin是Meteor框架的扩展,因为它需要能够找到您编写的代码(您的集合)才能正常工作。

如何启用此功能取决于您。以前的集合是全局定义的,因此它们(自动/急切地)导入,并且通常在/client/server目录之外,因此它们可以在客户端和服务器上访问。

现在您可以选择 - define your collections outside the /imports directory, and they will still be eagerly imported,或者在管理框架需要它们的地方导入它们。作为第三种方式,您可以要求将它们附加到(服务器端)global对象,例如作为dict(即global.myCollections = {'posts': Posts})和(在浏览器中)window对象(window.myCollections = {'posts': Posts})。

yogiben:admin' example starter repo将所有内容保存在/imports之外,但我怀疑如果您将集合定义保留在/imports之外,这仍然可以正常运行代码的其余部分到currently recommended project structure

答案 1 :(得分:0)

我不认为Meteor有办法让内部的应用程序定义所有集合。

要实现这一点,您可以覆盖Mongo.Collection方法以保留对每个已创建集合的引用。

const _oldCollection = Mongo.Collection;

Mongo.Collection = function(name, options) {
  const c = new _oldCollection(name, options);

  Meteor.myCollections[name] = c;

  return c;
};

然后将其用作:

// define new collection
new Mongo.Collection('questions');

// retrieve collection
const c = Meteor.myCollections['questions'];

在使用Mongo.Collection定义新集合之前,请确保用于覆盖totamt的代码。