1

我使用以下领域SimpleSchema,autoValue用于更新不设置给定值

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

+0

究竟是什么你试图达到? – Styx

+0

@Styx:用粗体修改最后一行。提前致谢。 –

+0

也许,'defaultValue'是你需要的吗? – Styx

回答

0

您应该处理2种情况:

  1. 文件insert空(未定义)valuefileNo

  2. 文件号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 
    } 

新增:用来写这个答案文档(代码按预期工作;本地测试):

+0

再次感谢。你节省了我很多时间,这是我无法解决的非常狭窄的情况:) –

+0

@AnkurSoni不客气:)阅读文档彻底帮助了很多;) – Styx

+0

你能不能指出文档的链接和行号?在你的回答中? –