Meteor – Insert Sample Data if the MongoDB is empty

Say we have a Meteor collection called Student.

model.js

Student = new Meteor.Collection('student');

 

So i would like to have some predefined students if the collection is emtpy. So i prepare the student.json in the private folder.

private/student.json

{
  "student":
  [
    { "_id": "1", "name": "Peter" },
    { "_id": "2", "name": "Jack" },
    { "_id": "3", "name": "Mary" },
    { "_id": "4", "name": "Sam" },
    { "_id": "5", "name": "Ann" },
  ]
}

 

Let’s configure the server.js such that it will insert the above json if the collection is empty.

server/server.js

Meteor.startup(function () {
  // Insert sample data if the student collection is empty
  if (Student.find().count() === 0) {
    JSON.parse(Assets.getText("student.json")).student.forEach(function (doc) {
      Student.insert(doc);
    });
  }
});

 

Done =)

Reference: Meteor Documentation – Assets.getText(assetPath, [asyncCallback])

Advertisements

4 thoughts on “Meteor – Insert Sample Data if the MongoDB is empty”

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s