2015-02-10 47 views
4

Collection2的文档说明了如何创建Schema以及如何将模式附加到集合,但我认为缺少一个带插入/更新窗体,错误处理和没有autoform的完整工作示例。如何在工作流星项目上实现Collection2?

如何更改现有项目以使用Collection2?具体来说:

  • 我还需要check(Meteor.userId(), String);吗?
  • 我不再需要拨打check()吗?
  • 我可以删除我的验证码吗?我只需拨打insert(),Collection2将会捕获所有错误,这要感谢架构?
  • 还有什么我应该改变?

这里从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; 
} 

这将如何代码看起来更新时使用Collection2样?

+1

如果您想充分利用它,这种软件包需要进行一些更改。但是,如果你确实提供了一些代码,比如数据库CRUD意图验证代码,服务器方法检查代码,客户端代码,这将对你有所帮助。通过这种方式,我们可以举例说明如何更新代码以适合collection2,或者可能评论/改正你的尝试。 – 2015-02-10 12:07:01

+0

谢谢,我添加了服务器端代码。 – aBe 2015-02-10 12:27:39

回答

1

我和你一样,我基本上使用autoform执行keyUp验证,就是这样。 简而言之,collection2将运行相当于_.pick,跳过空字符串,尝试强制输入到模式类型,验证文档并运行模式自动值函数。

check()不会尝试强制值,所以在某些边缘情况下,它很有用,但通常没有必要。

它的验证只是防止插入。因此,您仍然需要一些代码来改善用户体验&向他们展示他们已经搞砸的位置。