流星预填充 collection

Meteor prefill a collection

我在流星中做了以下collection:

CodesData = new Mongo.Collection('CodesData');

CodesDataSchema = new SimpleSchema({
    code: {
        label: "Code",
        type: Number
    },
    desc: {
        label: "Description",
        type: String,
    }
});

CodesData.attachSchema(CodesDataSchema);

现在我想用一些数据预填充此 collection。 例如:代码:1 desc:"hello"。 我怎样才能轻松地手动执行此操作?

服务器应用程序加载并启动后,您可以使用 Meteor.startup 对您的集合进行 运行 一些操作:

CodesData = new Mongo.Collection('CodesData'); 
CodesDataSchema = new SimpleSchema({ code: { label: "Code", type: Number }, desc: { label: "Description", type: String, } }); 
.attachSchema(CodesDataSchema);

Meteor.startup(()=>{
  // Only fill if empty, otherwise
  // It would fill on each startup
  if (CodesData.find().count() === 0) {
    CodesData.insert({ code: 1, description: 'some description' });
  }
});

如果你有很多数据要预填充,你可以在 JSON 中定义它并在启动时加载它:

考虑以下 json 命名为 pre

{
  codesdata: [
    { code: 1, description: 'foo' },
    { code: 7, description: 'bar' }
  ]
}

Meteor.startup(()=>{
  const preData = JSON.parse( pre );
  preData.codesData.forEach( entry => {
    CodesData.insert( entry );
  });
});

这使您可以更轻松地管理预填充,还可以让您根据需要对 json 进行版本控制(并且不会泄露任何敏感数据)。

考虑因素:

函数 Meteor.startup 运行 每次启动。因此,您应该考虑如何避免产生双打的不必要的插入/预填充。一个好方法是检查集合是否为空(参见第一个示例)。

您可以将启动代码放在另一个 js 文件中,以便将定义与启动例程分开。

当前脚本不区分服务器或客户端。您应该考虑在服务器上执行此操作并围绕它创建发布/订阅。

更多阅读:

https://docs.meteor.com/api/core.html#Meteor-startup

Importing a JSON file in Meteor

https://docs.meteor.com/api/core.html#Meteor-settings