In a meteor web app, is having both a SimpleSchema and a ValidatedMethod redundant? When trying to reuse the previously defined schema I get a syntax error.
Here is what I mean:
mycollection.js
export const myCollection = new Mongo.Collection('myCollection');
export const mySchema = new SimpleSchema({
a_field:String;
});
myCollection.attachSchema(mySchema);
Now for the insert method:
methods.js
import {mySchema, myCollection} from mycollection.js;
export const insertMethod = new ValidatedMethod({
name:'insertMethod',
validate:new SimpleSchema({
mySchema, /*Shows a syntax error: How to avoid repeating the schema?*/
}).validator(),
run(args){
myCollection.insert(args);
}
});
For this simple example, it would be "ok" to rewrite a_field:String
to the validated method's Schema. For more complicated examples however this seems pretty redundant, and what about if I want to use some of the previously defined schema and add some new fields for validation without having to copy the whole thing over?
I had the same problem as you before, this is what I did:
import { ValidatedMethod } from 'meteor/mdg:validated-method';
import { Reviews } from '../../Reviews/Reviews.js';
export const insertReview = new ValidatedMethod({
name: 'insertReview',
validate: Reviews.simpleSchema().validator(),
run(data) {
// ...
}
});
If you need exclude some fields:
import { ValidatedMethod } from 'meteor/mdg:validated-method';
import { Reviews } from '../../Reviews/Reviews.js';
const newReviewsSchema = Reviews.simpleSchema().omit([
'field1',
'field2',
]);
export const insertReview = new ValidatedMethod({
name: 'insertReview',
validate: newReviewsSchema.validator(),
run(data) {
// ...
}
});
And when you need to extend the schema:
import { ValidatedMethod } from 'meteor/mdg:validated-method';
import { Reviews } from '../../Reviews/Reviews.js';
export const insertReview = new ValidatedMethod({
name: 'insertReview',
validate: new SimpleSchema([
Reviews.simpleSchema(),
new SimpleSchema({
newField: {
type: String,
}
}),
]).validator(),
run(data) {
// ...
}
});