【问题标题】:Meteor: JSON doesn't match SimpleSchemaMeteor:JSON 与 SimpleSchema 不匹配
【发布时间】:2015-12-13 20:12:41
【问题描述】:

我在我的流星应用程序中获得了这个 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 有什么问题。我可以更改它们以匹配最佳方式。

【问题讨论】:

    标签: json meteor simple-schema


    【解决方案1】:

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

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

    之后,您可以扩展/定义对象字段,例如,

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

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

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

    【讨论】:

      【解决方案2】:

      最简单的解决方案是在您的架构中将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 }
      }));
      

      【讨论】:

      • 如果我想在category 中有element: anything(如JSON数据中所示),那么我必须定义一个子模式吗?你能给我一个例子吗 - 假设 JSON 数据是我需要的格式?
      • 类似category: { type: [new SimpleSchema({ element: {type: String, optional: true}})], optional: true }?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-23
      • 1970-01-01
      • 2017-06-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多