mongodbmeteormeteor-collection2simple-schema

Meteor app crashes when trying to populate collections


This code works:

Schemas.City = new SimpleSchema({
    name: {
        type: String,
        label: 'City',
        unique: true
    }
});

Cities = new Mongo.Collection('cities');
Cities.attachSchema(Schemas.City);

This code works:

Meteor.startup(function() {
}

This code works:

Cities.insert([{
    name: 'Warszawa'
}, {
    name: 'Krakow'
}]);

But this code doesn't:

Meteor.startup(function() {
    if (Cities.find().count() == 0) {
        Cities.insert([{
            name: 'Warszawa'
        }, {
            name: 'Krakow'
        }]);
    }
}

I'm having the following error in console on server:

W20150911-13:34:52.281(4)? (STDERR) Error: 0 is not allowed by the schema
W20150911-13:34:52.281(4)? (STDERR)     at getErrorObject (packages/aldeed:collection2/collection2.js:417:1)

As you can see, I use aldeed:collection2 package to control data manipulations so that they stick to schema. The schema is simple and it only requires that there are no duplicates.

What's the right direction to move to discover the problem? Am I missing something?

Update: no arrays when inserting in Meteor

Okay, I got it. In Meteor, it's not possible to insert multiple entries into a collection using

Collection.insert([entry1, entry2, ...])

syntax. This, in turn, works:

Collection.insert(entry1);
Collection.insert(entry2);

So the problem is solved, mostly partially.


Solution

  • batchInsert should be used in Meteor instead of insert in this case:

    Collection.batchInsert([entry1, entry2, ...])