thatgibbyguy
thatgibbyguy

Reputation: 4103

Meteor Simple Schema validating object

I have defined a schema for a meteor mongo collection using smpl-schema and I'm getting some confusing behavior. I'm trying to define an Array of Objects which validates fine, but on insert fails.

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

The validate method validates fine. But when I insert

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

I get Error: After filtering out keys not in the schema, your object is now empty

How could validate pass but insert fail?

Upvotes: 1

Views: 717

Answers (1)

jdsplit
jdsplit

Reputation: 26

There is a Validate method to validate yourself an object against a predefined schema, but in the case of a collection, you only need to attach the schema itself, not the result of the validation.

So this should work :

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

Upvotes: 1

Related Questions