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?