我在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 : "-"

最佳答案

您应该处理两种情况:


insert为空的(未定义)value文档fileNo
文档update,其中value为空的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
  }


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


aldeed:meteor-collection2#autovalue
aldeed:meteor-simple-schema#autovalue

09-05 17:46