Search code examples
jsonmeteorsimple-schema

Meteor: JSON doesn't match SimpleSchema


I got this SimpleSchema for a collection in my meteor-app

Collection.attachSchema(new SimpleSchema({
    title:                  { type: String },
    slug:                   { type: String, unique: true },
    language:               { type: String, defaultValue: "en" },
    'category.element':     { type: String, optional: true }
}));

And I try to insert this JSON-data, but I get insert failed: Error: Category must be an object at getErrorObject

{
    "_id" : "25uAB4TfeSfwAFRgv",
    "title" : "Test 123",
    "slug" : "test_123",
    "language" : "en",
    "category" : [
        {
            "element" : "Anything"
        }
    ]
}

What is wrong with my JSON-data? Or what's wrong with my SimpleSchema. I can change both of them to match the best way.


Solution

  • The simplest solution is to define category as an array of objects in your schema:

    Collection.attachSchema(new SimpleSchema({
        title:       { type: String },
        slug:        { type: String, unique: true },
        language:    { type: String, defaultValue: "en" },
        category:    { type: [Object], optional: true }
    }));
    

    This will get you unstuck.

    If you want to be more specific about the contents of category then you can define a sub-schema for category. For example:

    CategorySchema = new SimpleSchema({
        element:     { type: String }
    });
    
    Collection.attachSchema(new SimpleSchema({
        title:       { type: String },
        slug:        { type: String, unique: true },
        language:    { type: String, defaultValue: "en" },
        category:    { type: [CategorySchema], optional: true }
    }));