簡體   English   中英

AutoForm中沒有使用Meteor方法設置AutoValue

[英]AutoValue not set in AutoForm with Meteor method

我有一個使用autoform,collection2和簡單模式創建的插入表單。 createdBy字段填充使用autovalue的用戶ID。 當使用meteor.allow()進行插入時,該表單有效,但我想用方法替換allow,以便我可以對用戶角色進行一些驗證,即確保用戶具有管理員權限。 但現在我得到一個錯誤,即createdBy字段為空。

開發工具中的錯誤是:

錯誤:400,原因:“創建者是必需的”,詳細信息: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);來清理對象Courses.simpleSchema().clean(course); 在服務器方法中,以便安全地添加自動和默認值。 另外,請注意, this.userIdautoValue功能是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(); 
        }
    },

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM