【问题标题】:autoValue in SimpleSchema for update does not set given value用于更新的 SimpleSchema 中的 autoValue 未设置给定值
【发布时间】:2018-03-16 23:56:58
【问题描述】:

我在 SimpleSchema 中使用以下字段,

  "fileNo": {
    type: String,
    label: "File No.",
    autoValue: function() {
      console.log('this', this);
      console.log('typeof this.value.length ', typeof this.value.length);
      console.log('this.value.length ', this.value.length, this.value.length === 0, this.value.length == 0);
      console.log('this.value ', this.value, typeof this.value);
      console.log('this.operator ', this.operator);
      console.log('this.isSet ', this.isSet);
            if ( this.isSet && 0 === this.value.length ) {
                console.log('if part ran.');
                return "-";
            } else {
              console.log('else part ran.');
            }
        },
    optional:true
  },

我正在使用autoformupdate 一个字段。问题是当我使用空字符串 (即保持文本框为空) 更新字段时,值 - 未按照上面 SimpleSchema 代码中的字段定义设置。

我得到如下日志,

clients.js:79 this {isSet: true, value: "", operator: "$unset", unset: ƒ, field: ƒ, …}
clients.js:80 typeof this.value.length  number
clients.js:81 this.value.length  0 true true
clients.js:82 this.value   string
clients.js:83 this.operator  $unset
clients.js:84 this.isSet  true
clients.js:86 if part ran.
clients.js:79 this {isSet: true, value: "-", operator: "$unset", unset: ƒ, field: ƒ, …}
clients.js:80 typeof this.value.length  number
clients.js:81 this.value.length  1 false false
clients.js:82 this.value  - string
clients.js:83 this.operator  $unset
clients.js:84 this.isSet  true
clients.js:89 else part ran.    

而我的收藏文档没有字段fileNo

我错过了什么?我想要的只是当fileNo 的值为empty/undefined 时,值必须设置为-(连字符)。在文档中它必须看起来像fileNo : "-"

【问题讨论】:

  • 你到底想达到什么目的?
  • @Styx:用粗体修改最后一行。提前致谢。
  • 也许,defaultValue 是您所需要的?
  • 那也行不通。因为this.isSettrue,所以它已经在使用empty 字符串,所以它不使用defaultValue
  • 你使用的是什么版本的simple-schema

标签: javascript meteor ecmascript-6 meteor-autoform simple-schema


【解决方案1】:

你应该处理两种情况:

  1. 文档insert 为空(未定义)value 用于fileNo

  2. 文档updatevalue 为空fileNo

在第二种情况下,如果字段的值为空字符串 (optional: true),验证器将尝试从文档中删除该字段。我们可以捕捉并防止这种情况发生。

  fileNo: {
    type: String,
    label: 'File No.',
    autoValue() {
      if (this.isInsert && (this.value == null || !this.value.length)) {
        return '-';
      }
      if (this.isUpdate && this.isSet && this.operator === '$unset') {
        return { $set: '-' };
      }
    },
    optional: true
  }

添加:用于编写此答案的文档(代码按预期工作;在本地测试):

【讨论】:

  • 再次感谢您。你节省了我很多时间,这是我无法解决的非常狭窄的案例:)
  • @AnkurSoni 不客气 :) 彻底阅读文档有很大帮助 ;)
  • 您能否在答案中指出文档的链接和行号?
  • @AnkurSoni 更新了我的答案
  • 您可以签约吗?
猜你喜欢
  • 2016-05-31
  • 1970-01-01
  • 2017-04-07
  • 1970-01-01
  • 2016-06-20
  • 1970-01-01
  • 1970-01-01
  • 2018-01-07
  • 1970-01-01
相关资源
最近更新 更多