How to validate document-objects via SimpleSchema or check?

Hi guys,

I’d love to know how to do this. How do I check if a passed parameter is a doc of a specific collection?

// using SimpleSchema && Collection2
const MyCollection = new Mongo.Collection('mycollection')
const MySchema = {
  text: { type: String },
}
MyCollection.attachSchema(MySchema)

// HOW do I now validate that doc is a MyCollection-doc?
const docId = MyCollection.insert({ text: 'text' })
const doc = MyCollection.findOne(docId)
doSomething({ doc })
const doSomething = (options={}) => {
  new SimpleSchema({
    doc: { type: MySchema },  // throws a ``Error: Doc must be an object [validation-error]``
  }).validate(options)
  check(options.doc, MySchema)  // does NOT work. it passes, but does NOT validate
}

Since you are using collection2, there is nothing you have to manually do. Validation will run during insert and update automatically.

Yeah, of course I know!

BUT there are useCases where you want to validate manually using SimpleSchema.validate(). Please have another look at the code above - the doSomething-method is what this question is about. Here I am using SimpleSchema to validate the options of the functions.

const doSomething = (options={}) => {
  new SimpleSchema({
    doc: { type: MySchema },  // throws a ``Error: Doc must be an object [validation-error]``
  }).validate(options)
  check(options.doc, MySchema)  // does NOT work. it passes, but does NOT validate

  // ok, now that I now that "doc" really is of type "Schema", go on do some stuff with it
}

Any other suggestions?

Having a closer look at your code, you seem to be using simple-schema in a weird way.

I think you may be looking for something more along these lines.

const MyCollection = new Mongo.Collection('mycollection')

const MySchema = new SimpleSchema({ //need a new SimpleSchema here
  text: { type: String },
});

MyCollection.attachSchema(MySchema);

const docId = MyCollection.insert({ text: 'text' });
const doc = MyCollection.findOne(docId);

doSomething({ doc });

const doSomething = (options={}) => {
  const context = MyShema.getContext(); //must get a validation context
  context.validate(options.doc); //and now we can validate the doc

  check(options.doc, MySchema)  // this should now work as long as your are not using the version from npm
}