Meteor:JSON与SimpleSchema不匹配

时间:2015-09-12 20:54:08

标签: json meteor simple-schema

我在meteor-app中收集了这个SimpleSchema集合

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

我尝试插入此JSON数据,但我得到insert failed: Error: Category must be an object at getErrorObject

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

我的JSON数据有什么问题?或者我的SimpleSchema有什么问题。我可以改变它们以匹配最佳方式。

2 个答案:

答案 0 :(得分:1)

您需要先声明对象,例如

Collection.attachSchema(new SimpleSchema({
    ...,
    ....,
    category: {type: [Object], optional: true}
}));

之后,您可以扩展/定义像

这样的对象字段
Collection.attachSchema(new SimpleSchema({
    ....,
    ....,
    category: {type: [Object]},
    'category.$.element': {type: String}
}));

使用' $'如果它是一个数组对象([对象]),如果只有对象,则不要使用' $'。
如果您不确定对象结构,请使用另一个参数blackbox:true 等,

category: {type: [Object], blackbox: true}

答案 1 :(得分:0)

最简单的解决方案是在您的架构中将category定义为对象数组

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

这会让你失意。

如果您想更加具体地了解category的内容,那么category可以define a sub-schema。例如:

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