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])

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

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.