如果有的话,流星用数据库中的数据填充表格,如果没有则显示表格

Meteor fill a form with data from database if there is one, if not show the form

我正在学习如何使用 MeteorJS。我正在尝试用数据库中的 return 预填表格,所有文本输入都没有问题,但我怎么能检查收音机呢?我从数据库中得到的是一个很长的表格,至少有 150 个字段。所以我将不得不经常处理这个问题,但我不知道如何处理。显然我已经检索到正确的文档,所有其他字段都很好,收音机的值也很好,但是我如何使用 handlebars o 任何其他方式将 checked 属性添加到它们。

Template.myTemp.helpers({
   full : function () {
      var id = Session.get('currentId');
      if (id) {
         return People.findOne({_id: id});
      } else {
         return true;
      }
   }
});

ok,所以这里的 return true 只是为了在没有定义 Session 的情况下显示没有预填充值的表单。接下来是我的模板的简短版本

<template name="myTemp">
  {{#with full}}
  <div class="input-field">
        <label for="name" class="active">Name</label>
        <input id="name" name="name" type="text" value= "{{name}}">
  </div>
  <p>
        <input id="fem" name="sex" type="radio" value="FEM" class="with-gap">
        <label for="fem">Female</label>
        <input id="male" name="sex" type="radio" value="MALE" class="with-gap">
        <label for="male">Male</label>
  </p>
  {{/with}}
</template>

所以这就是诀窍,当我使用此表单插入时效果很好,但在尝试预填充时,它是一场噩梦。如果我在 return 中获得的值是来自以性别名称存储在数据库中的表单的值,我该如何检查此单选按钮。

我假设您的 People 集合中的文档类似于以下对象:

{ "_id" : "adCsEGoHFbpJbFjtP", "name" : "John Doe", "sex" : "male" }
{ "_id" : "TYLDYicCzpHSD5Sk5", "name" : "Jane Doe", "sex" : "female" }

如果是这种情况,您可以在 myTemp 模板中定义一个助手,如果文档的属性 type 与函数的参数匹配,则 returns 字符串 checked :

if (Meteor.isClient) {
    Template.myTemp.helpers({
        full: function () {
            var id = Session.get('currentId');
            if (id) return People.findOne({_id: id});
            else return true;
        },
        isChecked: function (type) {
            return (this && this.sex === type) ? 'checked' : null;
        }
    });
}

People = new Mongo.Collection("people");

if (Meteor.isServer) {
    Meteor.startup(function () {
        People.insert({
            "name": "John Doe",
            "sex": "male"
        });
        People.insert({
            "name": "Jane Doe",
            "sex": "female"
        });
    });
}

<template name="myTemp">
    {{#with full}}
        <div class="input-field">
            <label for="name" class="active">Name</label>
            <input id="name" name="name" type="text" value="{{name}}">
        </div>
        <p>
            <input id="fem" name="sex" type="radio" value="FEM" class="with-gap" {{isChecked 'female'}}>
            <label for="fem">Female</label>
            <input id="male" name="sex" type="radio" value="MALE" class="with-gap" {{isChecked 'male'}}>
            <label for="male">Male</label>
        </p>
    {{/with}}
</template>

这里是MeteorPad.