how to set a default value to element in a collect

2019-07-17 15:22发布

问题:

i have quickform once the submit button clicked, this method is fired

submitPost: function (app) {
    check(app, {
      title: String,
      description: String,
      category: String,
      price: Number
    });
    var knownId = Products.insert(app);
    Products.update({ _id: knownId }, { $set:{screenShots: scs, previewImage: pi, sourceCode: zip }});

  }

the submit button wasn't working when i didn't give "screenShots, previewImage, and sourceCode" a default values in a collection.

Once i gave them a default value like it is shown below

previewImage: {
    type: String,
    defaultValue: "jjj",
  },
   sourceCode: {
    type: String,
    defaultValue: "jjj",
  },
  screenShots: {
    type: [String],
    autoValue: function() {
      return [];
    }
  },

now the submit button in the form is working and the update method is triggered. it updates both "previewImage and sourcCode" but "screenShots" is still empty.

am not sure but i believe the problem has to do with autoValue which i should make it a default value, but how do i give an element that of type array of string a default value?

or the problem has to do with something else?

回答1:

use optional: true in the schema if the value is optional, and it will pass check if it is empty.



回答2:

The autoValue option is provided by the SimpleSchema package and is documented there. Collection2 adds the following properties to this for any autoValue function that is called as part of a C2 database operation:

  • isInsert: True if it's an insert operation
  • isUpdate: True if it's an update operation
  • isUpsert: True if it's an upsert operation (either upsert() or upsert: true)

So If you want to provide the autoValue while updating you have to use isUpdate in your schema like this.

createdAt: {
    type: Date,
    autoValue: function() {
      if (this.isInsert) {
        return new Date();
      } else if (this.isUpsert) {
        return {$setOnInsert: new Date()};
      } else {
        this.unset();  // Prevent user from supplying their own value
      }
    }
},

So your schema will be something like this:

previewImage: {
    type: String,
    defaultValue: function() {
         if (this.isInsert) {
            return 'fff';
         } else if (this.isUpdate) {
            return 'fff';
         }
  },
   sourceCode: {
    type: String,
    defaultValue:function() {
         if (this.isInsert) {
            return 'jjj';
         } else if (this.isUpdate) {
            return 'jjj';
         }
  },
  screenShots: {
    type: [String],
    autoValue: function() {
         if (this.isInsert) {
            return [];
         } else if (this.isUpdate) {
            return [];
         }
    }
},

For more info please check this