【问题标题】:How to prevent false values from being added in meteor-autoform and SimpleSchema如何防止在meteor-autoform和SimpleSchema中添加错误值
【发布时间】:2020-09-26 00:19:04
【问题描述】:

我在 Meteor 应用程序中有一个带有附加 SimpleSchema 的 MongoDB 集合。在前端,我使用meteor-autoform 包中的quickform 来快速呈现表单。 (https://github.com/Meteor-Community-Packages/meteor-autoform)

export const MyCollection = new Mongo.Collection('my-collection');
export const MySchema = new SimpleSchema({

  name: {
    type: String
  },

  isSuperDuper: {
    type: Boolean,
    optional: true
  }

});

MyCollection.attachSchema(MySchema);

const exampleDoc = { name: 'Waka Waka' };
MyCollection.insert(exampleDoc);

前端表单:

{{> quickForm collection="MyCollection" doc=myDoc id="updateMyDoc" type="update"}}

quickform 使用 isSuperDuper 布尔值加载我的 exampleDoc,该布尔值为 false。我在控制台的客户端上看到它AutoForm.getFormValues('updateMyDoc') 如果我检查mongo shell,没有isSuperDuper 键,正如预期的那样。第二次我保存了 quickForm(不做任何更改),文档被分配了isSuperDuper: false

是否可以使用 quickform 而不自动将我的架构中的空布尔值转换为 false 值?

我尝试过使用快速表单设置 autoConvert=falseremoveEmptyStrings=false 无济于事。

感谢您的帮助。

【问题讨论】:

  • 这里还有其他因素在起作用。 SimpleSchema 将定义您的模式并对其进行验证,但不会插入其他属性。您可能想分享更多关于“插入”的代码吗?
  • 谢谢@Chase,你是对的。问题来自客户端上使用的 autoform quickform。我已经更新了我的问题。
  • 您是否在表单中使用了复选框?一个复选框只有两个值——真或假。相反,您需要使用允许第三种“未定义”状态的选择或单选。
  • Quickform会根据schema自动生成表单,我没有手动添加任何字段。它呈现一个名为“名称”的文本字段,其中已经填充了我的“Waka Waka”值。然后是未选中的名为“isSuperDuper”的复选框。

标签: javascript mongodb meteor schema


【解决方案1】:

我猜问题是您使用的是默认的“复选框”,它只有两种可能的状态(选中/未选中)。未选中将映射到false

请参阅文档的这一部分:https://github.com/Meteor-Community-Packages/meteor-autoform#affieldinput

If you don't include a type attribute, the following logic is used to automatically select an appropriate type:

...


* Otherwise if the schema type is Boolean, the boolean-checkbox
  type is used. You may want to specify a type of boolean-radios
  or boolean-select instead. If you do so, use the trueLabel,
  falseLabel, and nullLabel attributes to set the labels used 
  in the radio or select control.

这听起来像您可以指定单选或选择选项以允许空状态,这可能会为可选的布尔值产生更好的结果(本质上是给它第三种状态)。

【讨论】:

  • 从上图:Quickform根据schema自动生成表单,我没有手动添加任何字段。它呈现一个名为“名称”的文本字段,其中已经填充了我的“Waka Waka”值。然后是未选中的名为“isSuperDuper”的复选框。
  • 我知道,这解释了为什么这是一个问题。未选中的复选框表示false
  • 这让我们回到了我最初的问题:是否可以使用 quickform 而不会自动将我的架构中的空布尔值转换为错误值?
  • 是的,正如我所描述的。您没有说明要求它必须在表单中显示为复选框。这就是存在其他两种类型的原因。
  • 它的形式无关紧要。尽管如 OP 中所述,它必须使用 quickform。
猜你喜欢
  • 2016-01-08
  • 1970-01-01
  • 2017-10-05
  • 1970-01-01
  • 1970-01-01
  • 2016-06-19
  • 1970-01-01
  • 1970-01-01
  • 2016-08-14
相关资源
最近更新 更多