流星:JSON 与 SimpleSchema 不匹配

Meteor: JSON doesn't match SimpleSchema

我在我的 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 有什么问题。我可以更改它们以匹配最佳方式。

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

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

这会让你摆脱困境。

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

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

你需要先声明对象,比如,

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

之后您可以 extend/define 对象字段,例如,

Collection.attachSchema(new SimpleSchema({
    ....,
    ....,
    category: {type: [Object]},
    'category.$.element': {type: String}
}));

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

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