fangio
fangio

Reputation: 1786

Meteor prefill a collection

I have made the following collection in meteor:

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

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

CodesData.attachSchema(CodesDataSchema);

Now I want to prefill this collection with some data. For example: code: 1 desc: "hello". How can I do this manually and easily?

Upvotes: 0

Views: 83

Answers (1)

Jankapunkt
Jankapunkt

Reputation: 8423

You can use Meteor.startup to run some actions on your collection once the server app has been loaded and is starting:

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' });
  }
});

If you have a lot of data to prefill you can define it in a JSON and load it on startup:

Consider the following json named as pre:

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

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

This allows you to manage your prefill more easily and also let's you version control the json if desired ( and no sensitive data is revealed ).

Considerations:

The function Meteor.startup runs on each start. So you should consider how to avoid unnecessary inserts / prefill that create doubles. A good way is to check if the collection is empty (see first example).

You may put the startup code an another js file in order to separate definitions from startup routines.

The current script does not differentiate between server or client. You should consider to do this on server and create a publication / subscription around it.

More readings:

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

Importing a JSON file in Meteor

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

Upvotes: 3

Related Questions