Meteor Simple Schema Validate and clean object

#1

I have defined a schema for a meteor mongo collection using smpl-schema to validate and clean object before insert and update data.

import SimpleSchema from 'simpl-schema';
const schema = new SimpleSchema({
  name:String,
  age:Number,
  address:{
   type:String,
   optional:True
  }
}, {
  clean: true,
});

My data :

let doc = {
  name:' ',
  age:10,
}

Here my function validate data:

function validateData(){
let validationContext = schema.newContext();
validationContext.validate(doc);
if (!validationContext.isValid()) throw JSON.stringify(validationContext.validationErrors())

return true
}

But it’s error and it’s output : Error: Cannot convert undefined or null to object [ValidateDataError]

#2

First I believe you need to define the clean key as an object with the cleaning options defined like so:

clean: {
    filter: true,
    autoConvert: true,
    removeEmptyStrings: true,
    trimStrings: true,
    getAutoValues: true,
    removeNullsFromArrays: true,
  },

Next, since you are validating manually and not using Collection2, you’ll need to call the clean method manually.

1 Like
#3

could you explain, how to call it ?

#4

Sure, you just have to call the clean method on the schema and pass it the document. It will return a cleaned document that you can pass to the validate method.

function validateData(){
  let validationContext = schema.newContext();
  let cleanDoc = shema.clean(doc); //Clean the document before validation
  validationContext.validate(cleanDoc);
  if (!validationContext.isValid()) throw JSON.stringify(validationContext.validationErrors())
    return true
}
1 Like
#5

Yes, thank you. it’s done

1 Like
#6

You’re very welcome.