EugVal
EugVal

Reputation: 233

Avoiding redundancy when using both a SimpleSchema and a ValidatedMethod for a meteor collection?

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?

Upvotes: 0

Views: 70

Answers (2)

EugVal
EugVal

Reputation: 233

For completeness, this is what I ended up using although it follows quite naturally from the above answer (difference is that I use the Schema itself rather than retrieving it from the collection):

import {mySchema, myCollection} from mycollection.js;

export const insertMethod = new ValidatedMethod({
    name:'insertMethod',
    validate:new SimpleSchema([ 
        mySchema,          
    ]).validator(),
    run(args){
        myCollection.insert(args);
    }
});

Upvotes: 0

kkkkkkk
kkkkkkk

Reputation: 7738

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) {
    // ...
  }
});

Upvotes: 1

Related Questions