Meteor Simple Schema验证对象

时间:2017-06-24 16:59:17

标签: mongodb validation meteor

我使用smpl-schema为meteor mongo集合定义了一个模式,并且我得到了一些令人困惑的行为。我试图定义 Objects Array ,它验证正常,但插入失败。

import SimpleSchema from 'simpl-schema';

const Schemas = {};

const resourceCollection = new Mongo.Collection('resourcecollection');

Schemas.resourceCollectionSchema = new SimpleSchema({
  resourceTypes: {
    type: Array,
    label: `The resources for a this collection`
  },
  "resourceTypes.$": {
    type: Object,
    blackbox: true
  },
  "resourceTypes.$.blah": {
    type: String
  }
}).validate({
  resourceTypes: [
    {
      "blah": "blah"
    }
  ]
});

验证方法验证正常。但是当我插入

resourceCollection.insert({
  resourceTypes: [
    {
      "blah": "blah"
    }
  ]
});

我得到Error: After filtering out keys not in the schema, your object is now empty

如何验证通过但插入失败?

1 个答案:

答案 0 :(得分:1)

有一个Validate方法可以根据预定义的模式验证自己的对象,但是对于集合,您只需要附加模式本身,而不是验证的结果。

所以这应该有效:

const resourceCollection = new Mongo.Collection('resourcecollection');

Schemas.resourceCollectionSchema = new SimpleSchema({
  resourceTypes: {
    type: Array,
    label: 'The resources for a this collection'
  },
  "resourceTypes.$": {
    type: Object
  },
  "resourceTypes.$.blah": {
    type: String
  }
});

resourceCollection.attachSchema(Schemas.resourceCollectionSc‌​hema);