2017-04-23 83 views
0

創建新用戶帳戶時,我使用Accounts.onCreateUser函數將數據插入到新集合中。我想在插入之前檢查插入是否成功。我的代碼似乎工作,但它似乎非常混亂。我想知道是否有更清晰的方式來編寫此代碼。Accounts.onCreateUser清理我的代碼

Accounts.onCreateUser((options, user) => { 
    if (user) { 
    CandidateProfile.insert({ 
     userId: user._id, 
     firstName: options.profile.name.first, 
     lastName: options.profile.name.last 
    }); 

    var checkForNewCandidateProfile = CandidateProfile.findOne(
     { userId: user._id }, 
     { fields: { userId: 1 } } 
    ); 
    var userId = 
     checkForNewCandidateProfile && checkForNewCandidateProfile.userId; 

    if (userId === user._id) { 
     return user; 
    } 
    } 
}); 
+0

我是一個可行的有些驚訝。 afaik,insert是一個異步操作,並且您正在從集合中立即讀取數據。我會懷疑findOne()沒有找到任何東西。我真的好奇這是如何工作。無論通過有條件地返回用戶,是否表示如果寫入收集失敗,您希望註冊失敗? – zim

+0

當插入出現問題時,它已經失敗,並且在客戶端,用戶看到「出現內部服務器錯誤」。日誌顯示完整的錯誤。你說你很驚訝它的工作原理,這是我的問題,寫這個的正確方法是什麼? – bp123

+0

由於onCreateUser()意味着同步工作,因此Futures可能會在此上下文中提供類似同步的體驗。看看我的答案在這裏可能是什麼樣的:http://stackoverflow.com/a/43564544/3199246 – zim

回答

0

就我個人而言,在您的測試中我沒有看到任何意義。你不相信insert

但是好的,你需要它。

  1. 確保您在服務器端運行您的代碼。導入只在服務器端,或只是把它包在if (Meteor.isServer)

  2. 爲什麼檢查user ARG存在?就是這樣,這個回調是如何工作的。

  3. 如果出現錯誤,則拋出錯誤以中止用戶創建。

可能的變化:

if (Meteor.isServer) { 
    Accounts.onCreateUser((options, user) => { 
    // You insert sync, so it's up to you to handle errors. 
    try { 
     CandidateProfile.insert({ 
     userId: user._id, 
     firstName: options.profile.name.first, 
     lastName: options.profile.name.last 
     }); 

     var checkForNewCandidateProfile = CandidateProfile.findOne(
     { userId: user._id }, 
     { fields: { userId: 1 } } 
    ); 
     var userId = 
     checkForNewCandidateProfile && checkForNewCandidateProfile.userId; 

     if (userId === user._id) { 
     return user; 
     } 
    } catch (error) { 
     throw new Error(error); 
    } 
    throw new Error("Something's wrong."); 
    }); 
} 
+0

插入不失敗至關重要。我仍然對編碼不熟悉。檢查插入是否正常工作不正常嗎? – bp123

+0

這很正常。當你運行異步時,你有一個錯誤arg的回調來處理錯誤。另一方面,當你同步運行一些東西時,你可以用'try' /'catch'來處理錯誤。我不相信'插入'是100%正確的。沒有錯,可能會出現錯誤。 –