我在尝试将数据从集合填充到流星的aldeed:表格模块时遇到问题。
我的代码看起来像这样,是项目的根目录.js作为一个通用的文件。
下面的所有代码都在一个文件中:root/lib/hello.js
if (Meteor.isServer) {
Meteor.startup(function () {
// code to run on server at startup
database = new MongoInternals.RemoteCollectionDriver("mongodb://localhost:27017/mydb");
idpool = new Mongo.Collection("idpool", {_driver:database});
Meteor.publish('idpool', function(){
return idpool.find();
});
});
}
if (Meteor.isClient) {
Meteor.subscribe("idpool");
}
TabularTables = {};
Meteor.isClient && Template.registerHelper('TabularTables', TabularTables);
TabularTables.idpool = new Tabular.Table({
name: "idpool",
collection: idpool,
columns: [
{data: "_id", title: "id"}
]
});
表格代码必须是服务器和客户端可见的通用代码,但是当我运行上述内容时,未定义"idpool"集合(超出范围)。
Reference Error: idpool is not defined
将数据库声明移到范围之外的 JS 顶部,那么我就无法发布和订阅它。 即:
database = new MongoInternals.RemoteCollectionDriver("mongodb://localhost:27017/adaptiveid");
idpool = new Mongo.Collection("idpool", {_driver:database});
//rest of the code.....
如果我尝试通过代码的常见表格部分第二次添加,如下所示:
idpool = new Mongo.Collection("idpool");
我收到以下错误:
错误:已定义名为"/idpool/insert"的方法
我在这里做错了什么?如何声明数据库服务器端并将其公开给通用表格代码。
你应该把代码放在/lib 文件夹中
/lib
if(Meteor.isServer){
database = new MongoInternals.RemoteCollectionDriver("mongodb://localhost:27017/adaptiveid");
idpool = new Mongo.Collection("idpool", {_driver:database});
//rest of the code.....
}
为什么是isServer和/lib?好吧,/lib 文件夹是开始时加载的第一个流星,但该代码在客户端/服务器之间共享,这就是为什么您应该指定它仅在服务器中使用该代码的原因
请注意此处显示Error: A method named
'/idpool/insert' is already defined
,因为您要声明集合 idpool 两次。
idpool = new Mongo.Collection("idpool", {_driver:database})
您已经在那里声明了集合,为什么要声明两次?,只需删除第二个idpoll = new Mongo.Collection('idpool')
我也卡住了,文档只是说"在通用代码中定义你的表" - 所有这些都非常正确,但同样重要的是服务器和客户端都必须有权访问你的集合。
所以我发现,在单个文件中定义我的所有集合,创建一个"lib/collections.js"对我来说效果很好,所以我知道它们是否存在,并且当我重构时,我没有忘记它们何时加载,所以我会有这样的东西:
export const idpoll = new Mongo.Collection('idpool');
export const otherCollection = new Mongo.Colletionc('myOtherCollectin');
然后在我的代码中的其他任何地方,如果我需要该集合,我只需导入它:
import { idpoll } from './lib/collections.js' //ie. path to collections.js
在我的项目中,我有多个表,因此我决定创建一个 lib/init-tables.js 文件
export let TabularTables = {};
Meteor.isClient && Template.registerHelper('TabularTables',TabularTables);
然后对于每个表,我都有一个lib/myNameTable.js文件以及初始设置。
import { TabularTables } from './init-tables.js'; // Import TabularTables helper
import { idpoll } from './collections.js';
TabularTables.Regs = new Tabular.Table({
name: 'IDPOL',
collection: idpol,
columns: [
{data: 'field', title: 'fieldtitle'},line'},
...
]
});
<</div>
div class="one_answers"> 我确信在 lib 文件夹中声明新集合是标准做法,以便在其余代码运行之前创建它们将 idpool 行移动到 lib 并重试