由于缺少集合对象导致的 Collection2 关系错误

Collection2 relationship error due to missing collection object

我正在尝试在 2 个集合之间创建关系,但其中一个集合无法在另一个集合中引用。具体来说,我有 2 个集合:Sites 和 ContentTypes。这就是它们包括的内容:

// app/lib/collections/sites.js    
Sites = new Mongo.Collection('sites');

Sites.attachSchema(new SimpleSchema({
  name: {
    type: String,
    label: "Name",
    max: 100
  },
  client: {
    type: String,
    label: "Client",
    max: 100
  },
  created: {
    type: Date,
    autoValue: function() {
      if (this.isInsert) {
        return new Date;
      } else if (this.isUpsert) {
        return {$setOnInsert: new Date};
      } else {
        this.unset();  // Prevent user from supplying their own value
      }
    }
  }
}));

这是 ContentTypes 集合:

// app/lib/collections/content_types.js
ContentTypes = new Mongo.Collection('content_types');

ContentTypes.attachSchema(new SimpleSchema({
  name: {
    type: String,
    label: "Name",
    max: 100
  },
  machineName: {
    type: String,
    label: "Machine Name",
    max: 100
  },
  site:{
    type: Sites
  },
  created: {
    type: Date,
    autoValue: function() {
      if (this.isInsert) {
        return new Date;
      } else if (this.isUpsert) {
        return {$setOnInsert: new Date};
      } else {
        this.unset();  // Prevent user from supplying their own value
      }
    }
  }
}));

当我将站点引用添加到 ContentTypes 架构时,我的应用程序崩溃并出现错误:

ReferenceError: Sites is not defined at lib/collections/content_types.js:32:11

我在 collection2 中找到 this. It looks like the format referenced there is supposed to work based on this thread 之外的关系文档时运气不佳。

这是因为 Meteor 加载文件的顺序。请参阅文件加载顺序部分 here:

There are several load ordering rules. They are applied sequentially to all applicable files in the application, in the priority given below:

  1. HTML template files are always loaded before everything else
  2. Files beginning with main. are loaded last
  3. Files inside any lib/ directory are loaded next
  4. Files with deeper paths are loaded next
  5. Files are then loaded in alphabetical order of the entire path

例如将 app/lib/collections/sites.js 重命名为 app/lib/collections/a_sites.js 并且将在加载 content_types.js 文件时定义 Sites 变量。