在为流星集合使用SimpleSchema和ValidatedMethod时避免冗余?

时间:2016-11-28 05:14:25

标签: validation meteor simple-schema meteor-methods

在流星网络应用程序中,SimpleSchema和ValidatedMethod都是多余的吗?当尝试重用先前定义的模式时,我得到语法错误。

这就是我的意思:                                                                              mycollection.js

export const myCollection = new Mongo.Collection('myCollection');

export const mySchema = new SimpleSchema({
   a_field:String;
});

myCollection.attachSchema(mySchema); 

现在为插入方法: 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);
    }
});

对于这个简单的例子,将a_field:String重写为经过验证的方法的Schema是“没问题”。对于更复杂的例子,这似乎是多余的,如果我想使用一些先前定义的模式并添加一些新字段进行验证而不必复制整个事情呢?

2 个答案:

答案 0 :(得分:1)

我遇到了和以前一样的问题,这就是我所做的:

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

如果您需要排除某些字段:

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

当您需要扩展架构时:

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

答案 1 :(得分:0)

为了完整性,这是我最终使用的内容,尽管它很自然地遵循上述答案(不同之处在于我使用Schema本身而不是从集合中检索它):

import {mySchema, myCollection} from mycollection.js;

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