autoValue用于更新不设置给定值
我使用以下领域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
},
我使用autoform
到update
的字段。问题是当我使用空字符串(即保持文本框为空)更新字段时,值-
未按照上面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 : "-"
您应该处理2种情况:
文件
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
}
新增:用来写这个答案文档(代码按预期工作;本地测试):
再次感谢。你节省了我很多时间,这是我无法解决的非常狭窄的情况:) –
@AnkurSoni不客气:)阅读文档彻底帮助了很多;) – Styx
你能不能指出文档的链接和行号?在你的回答中? –
究竟是什么你试图达到? – Styx
@Styx:用粗体修改最后一行。提前致谢。 –
也许,'defaultValue'是你需要的吗? – Styx