AutoForm中没有使用Meteor方法设置AutoValue

时间:2016-02-18 22:38:49

标签: javascript meteor meteor-autoform meteor-collection2 meteor-methods

我有一个使用autoform,collection2和简单模式创建的插入表单。使用autovalue使用userId填充createdBy字段。使用meteor.allow()进行插入时表单有效,但我想用方法替换allow,以便我可以对用户角色进行一些验证,即确保用户具有管理员权限。但现在我收到createdBy字段为空的错误。

开发工具中的错误是:

  

错误:400,原因:"创建者是必需的",详情:undefined,   消息:"创建者需要[400]",errorType:" Meteor.Error"}

Courses = new Mongo.Collection('Courses');

courseSchema  = new SimpleSchema({
    title: {
        type: String,
        label: "Course Title"
    },
    description: {
        type: String,
        label: "Description"
    },
    createdAt: {
        type: Date,
        autoValue: function(){
            return new Date();
        },
        autoform:{
            type: 'hidden'
        }
    },
    startDate:{
        type: String,
        label: "Start Date"
    },
    sessions: {
        type: String,
        label: "No. of sessions"
    },
    duration: {
        type: String,
        label: "Duration of the course"
    },
    price: {
        type: String,
        label: "Course Price"
    },
    createdBy:{
        type: String,
        autoValue:function(){
            return this.userId;
        },
        autoform:{
            type:'hidden'
        }
    }
});

Courses.attachSchema(courseSchema);

该方法(可在客户端和服务器上使用):

Meteor.methods({
    addCourse: function(course){
        Courses.insert(course);
    }
});

生成表单的模板:

<template name="adminIndex">
   <h1>Available Courses</h1>
   {{> courseList }}    
   <button type="button" class="btn btn-success btn-block">Create New Course</button>
   <h3>Create New Course</h3>
   {{>quickForm id="InsertCourseForm" collection="Courses" type="method" meteormethod="addCourse"}}
</template>

2 个答案:

答案 0 :(得分:1)

您需要通过在服务器方法中调用Courses.simpleSchema().clean(course);来清理对象,以便安全地添加自动值和默认值。另请注意,this.userId函数中的autoValue对于服务器启动的操作是null,因此您可能希望将其替换为Meteor.userId()

此外,您必须通过调用Meteor方法中的check(value, pattern)来执行自己的验证,因为可以绕过客户端验证。

例如:

if (Meteor.isServer) {
  Meteor.methods({
    addCourse: function(course) {
      Courses.simpleSchema().clean(course);
      check(course, Courses.simpleSchema());
      Courses.insert(course);
    }
  });
}

答案 1 :(得分:1)

所以这有效,但我没有看到它在任何其他例子中使用,所以我有一种不好的感觉,但直到我能找到更多它将不得不做:

createdBy:{
    type: String,
    autoValue:function(){
        if(Meteor.isClient){
            return this.userId;
        }else if(Meteor.isServer){
            return Meteor.userId(); 
        }
    },