使用 Meteor 方法未在 AutoForm 中设置 AutoValue

AutoValue not set in AutoForm with Meteor method

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

开发工具中的错误是:

error: 400, reason: "Created by is required", details: undefined, message: "Created by is required [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>

您需要通过在服务器方法中调用 Courses.simpleSchema().clean(course); 来清理对象,以便安全地添加自动值和默认值。此外,请注意 autoValue 函数中的 this.userId 对于服务器启动的操作是 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);
    }
  });
}

所以这行得通,但我还没有看到它在任何其他示例中使用,所以我有一种不好的感觉,但在我找到更多信息之前,它必须这样做:

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