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

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

在 meteor web 应用程序中,同时拥有 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);
    }
});

对于这个简单的示例,"ok" 将 a_field:String 重写为已验证方法的架构。然而,对于更复杂的示例,这似乎是多余的,如果我想使用一些先前定义的模式并添加一些新字段进行验证,而不必复制整个内容呢?

我和你之前遇到了同样的问题,这就是我所做的:

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

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

import {mySchema, myCollection} from mycollection.js;

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