如何在架构中添加用户ID信息并隐藏表单自动形式?

Nai*_*air 1 meteor meteor-autoform simple-schema

我正在学习流星的绳索,有点迷失在这里.我正在使用collections2,autoform来构建我的应用程序.我想将该集合与用户ID信息一起存储.因此,当我们从服务器检索集合时,我想只显示用户创建的集合而不是其他所有集合.这是架构.

    ExercisesSchema = new SimpleSchema({
    "name": {
        type: String,
        label: 'Name'
    },
    "workout.$.weight": {
        type: String,
        label: 'Weight'
    },
    "workout.$.reps": {
        type: String,
        label: 'Reps'
    },
    "notes": {
        type: String,
        label: 'Notes',
        optional: true
    }
});
Run Code Online (Sandbox Code Playgroud)

在服务器端,我只想显示用户创建的锻炼

Meteor.publish('exercises', function () {
    return Exercises.find({owner: this.userId});
});
Run Code Online (Sandbox Code Playgroud)

当我将用户id添加到模式中时,它显示在autoform中,我不知道如何隐藏它,如果我隐藏它,那么我可以在autoform中使用钩子来添加值吗?

cha*_*ett 5

在架构中,您可以将ownerId定义为类型:"hidden"

schema.js

ExercisesSchema = new SimpleSchema({
    "name": {
        type: String,
        label: 'Name'
    },
    "ownerId": {
        type: String,
        autoform: {
            type: "hidden",
        }
    },
    "workout": {
        //not sure if you need this, you didn't have it in your
        type: [Object], 
        defaultValue: [] 
    },
    "workout.$.weight": {
        type: String,
        label: 'Weight'
    },
    "workout.$.reps": {
        type: String,
        label: 'Reps'
    },
    "notes": {
        type: String,
        label: 'Notes',
        optional: true
    }
});
Run Code Online (Sandbox Code Playgroud)

如你所说,用钩子填充它.

autoFormHooks.js

AutoForm.hooks({
  exerciseForm: {
    formToDoc: function(doc) {
      doc.ownerId = Meteor.userId();
      return doc
    },
  }
});
Run Code Online (Sandbox Code Playgroud)

使用钩子的另一种方法是在autoForm中为要在doc中设置的每个字段使用quickFields,包括ownerId.使用此解决方案,您可以将valueownerId 设置为currentUser.

{{#autoForm collection="Exercises" id="exerciseForm" type="insert"}}
  <fieldset>
    <legend>Add an Exercise</legend>
    {{> afQuickField name='name'}}
    {{> afQuickField name='notes'}}
    {{> afQuickField name='ownerId' value=currentUserId}}
    {{> afQuickField name='workout'}}
  </fieldset>
  <button type="submit" class="btn btn-primary">Insert</button>
{{/autoForm}}
Run Code Online (Sandbox Code Playgroud)

template.js

Template.formTemplate.helpers({
    currentUserId: function () {
        return Meteor.userId();
    }
});
Run Code Online (Sandbox Code Playgroud)