javascriptmeteorecmascript-6meteor-autoformsimple-schema

autoValue in SimpleSchema for update does not set given value


I am using below field in 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
  },

I am using autoform to update a field. The problem is when I am updating the field with empty string (i.e. keeping textbox empty), the value - is not set as per field definition in SimpleSchema code above.

I get logs as below,

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.    

and my collection document does not have field fileNo.

What am I missing? all I want is when value of fileNo is empty/undefined value must be set to - (hyphen). In document it must look like fileNo : "-"


Solution

  • You should handle 2 situations:

    1. Document insert with empty (undefined) value for fileNo.

    2. Document update with empty value for fileNo.

    In second case, validator will try to remove the field from the document if its value is empty string (optional: true). We can catch and prevent this.

      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
      }
    

    Added: documentation used to write this answer (code works as expected; tested locally):