4

The documentation for Collection2 explains how to create a Schema, and how to attach the Schema to a collection, but I think a full working example with insert/update forms, with error handling, and without autoform, is missing.

How do I change my existing project to make use of Collection2? Specifically:

  • Do I still need to check(Meteor.userId(), String); ?
  • Do I no longer need to call check() at all?
  • Can I delete my validation code? I simply call insert(), and Collection2 will catch all the errors thanks to the schema?
  • Anything else I should change?

Here sample code from DiscoverMeteor:

Meteor.methods({
  postInsert: function(postAttributes) {
    check(Meteor.userId(), String);
    check(postAttributes, {
      title: String,
      url: String
    });

    var errors = validatePost(postAttributes);
    if(errors.title || errors.url) {
      throw new Meteor.Error('invalid-post', 'Set a title and valid URL for your post');
    }

    var user = Meteor.user();
    var post = _.extend(postAttributes, {
      userId: user._id,
      author: user.username,
      submitted: new Date(),
      commentsCount: 0
    });

    var postId = Posts.insert(post);

    return {
      _id: postId
    };
  }
});

validatePost = function(post) {
  var errors = {};

  if(!post.title) {
    errors.title = "Please fill in a headline";
  }
  if(!post.url) {
    errors.url = "Please fill in a URL";
  } else if(post.url.substr(0, 7) != "http://" && post.url.substr(0, 8) != "https://") {
    errors.url = "URLs must begin with http:// or https://";
  }
  return errors;
}

How would this code look like when updated to use Collection2?

dayuloli
  • 16,205
  • 16
  • 71
  • 126
aBe
  • 422
  • 3
  • 9
  • 1
    Such a package would require some changes if you want to use it to the best of its capacities. But it would help _a lot_ if you did provide some code, such as database CRUD intent validation code, server method checking code, client code, ... This way we could give examples on how to update the code to fit collection2, or maybe comment/correct your tries. – Kyll Feb 10 '15 at 12:07
  • Thanks, I added the server side code. – aBe Feb 10 '15 at 12:27

1 Answers1

1

I'm in the same boat as you, I basically use autoform to perform keyUp validations and that's it. In a nutshell, collection2 is going to run the equivalent of a _.pick, skip empty strings, try to coerce inputs into schema types, validate the doc, and run the schema autovalue function.

check() won't try to coerce values, so in some edge cases, it's useful, but typically there's no need.

Its validation does little more than prevent an insert. Therefore, you'll still need some code to improve the user experience & show them where they messed up, which you've already got.

Matt K
  • 4,813
  • 4
  • 22
  • 35