编程语言
首页 > 编程语言> > javascript – 使用Meteor方法在AutoForm中未设置AutoValue

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

作者:互联网

我有一个使用autoform,collection2和简单模式创建的插入表单.使用autovalue使用userId填充createdBy字段.当使用meteor.allow()进行插入时,该表单有效,但我想用方法替换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()来清理对象.cleed(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);
    }
  });
}

标签:javascript,meteor,meteor-autoform,meteor-collection2,meteor-methods
来源: https://codeday.me/bug/20190702/1355571.html