2015-02-10 48 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()不會嘗試強制值,所以在某些邊緣情況下,它很有用,但通常沒有必要。

它的驗證只是防止插入。因此,您仍然需要一些代碼來改善用戶體驗&向他們展示他們已經搞砸的位置。

相關問題