Search code examples
meteormeteor-autoform

How to add a required dateSubmitted on the server with Meteor autoform?


I've got a Posts collection and the dateSubmitted field needs to be required. However, the value for this field should be generated on the server using server time.

Posts.attachSchema(new SimpleSchema({
  title: {
    type: String,
    optional: false
  },
  content: {
    type: String,
    optional: false
  },
  dateSubmitted: {
    type: Date,
    optional: false
  }
}));

The problem with this is that the form won't submit on the client if I only have values for title and content. But I also can't insert it into the collection without a dateSubmitted value that is generated from the server.

I looked at the Autoform hooks and nothing seems to work in this case.

This is my desired workflow:

  1. Schema says title, content, and dateSubmitted are required.
  2. The client submits the form successfully with only title and content.
  3. The server adds dateSubmitted
  4. The new document then gets inserted into the collection. 4.a. If for some reason the dateSubmitted can't be generated, an error gets sent back to the client.

Solution

  • Assuming you're already using aldeed:collection2 then in your schema use the following:

    dateSubmitted: {
        type: Date,
        autoValue: function(){
          if ( this.isInsert ) return new Date();
          else if ( this.isUpsert ) return { $setOnInsert: new Date };
          else if ( this.isSet ) this.unset();
        }
      }
    

    This will automatically set the date on insert/upsert and then reject all later changes.

    From http://0rocketscience.blogspot.com/2015/07/meteor-security-no-2-all-praise-aldeed.html