2016-01-29 34 views
0

該應用程序有兩種模型:用戶和帖子。查看用戶可以喜歡(upvote)由另一個用戶編寫的帖子。所以,我需要如何更新平均應用程序中的兩個模型

  1. 將帖子ID添加到查看用戶的喜歡數組。
  2. 將查看用戶的ID添加到喜歡該帖子的帖子的用戶數組。
  3. 增加作者的喜歡的計數器。

在高層次上,我找不出一個特別有吸引力的選項來處理這個問題。如果我製作了三個獨立的api路線,那麼在查看用戶喜歡的帖子時,會對服務器和數據庫進行三次不同的調用。

另一方面,如果我只有一個API路線,看起來它會太過分。此外,我相信我將有兩個嵌套調用數據庫:(?這是什麼原因興亞允許你這樣做)

//Pseudocode 
User.findById... // update the viewing user 
    Post.findById... // update the post 
     User.findById... // update the author user 

我用快遞,所以我不相信我可以鏈接連這些一個正確。我只能返回一個響應對象。

我該怎麼做?

回答

1

我認爲這更多的是你正在尋找的東西。我沒有測試過這個。我不完全確定rethrowError是需要的,但作爲一種預防措施,我將它放入,直到您可以進行一些測試。

export function update(req, res) { 
    updateUserById(req.params.voterId, res, userUpvoted(req.params.postId)) 
     .then(updatePostById(req.params.postId, res, postLikedBy(req.params.voterId))) 
     .then(updateUserById(req.params.authorId, res, userRecivedLike(req.params.voterId)) 
     .then(handleEntityNotFound(res)) 
     .then(responseWithResult(res)) 
     .catch(handleError(res)); 
    } 


    // ************ Update Functions ************ 
    function userUpvoted(postId) { 
    return function(user) { 
     // update the user's upVotes 
     return user; 
    } 
    } 

    function postLikedBy(userId) { 
    return function(post) { 
     // update the post's upVotes 
     return post; 
    } 
    } 

    function userRecivedLike() { 
    return function(entity) { 
     // update the post's upVotes with the entity object 
     return entity; 
    } 
    } 
    // ************ End Update Functions ************ 

    // ************ UpdateBy using using callback Functions ************ 
    function updateUserById(id, res, updateFunction) { 
    return User.findById(id) 
     .then(updateFunction(res)) 
     .catch(rethrowError); 
    } 

    function updatePostById(id, res, updateFunction) { 
    return Post.findById(id) 
     .then(updateFunction(res)) 
     .catch(rethrowError); 
    } 
    // ************ end UpdateBy using using callback Functions ************ 

    // ************ Helper Functions ************ 
    function rethrowError(err) { 
    throw err; 
    } 
    // ************ End Helper Functions ************ 
+0

那麼我還是要套它們?這是最佳做法嗎? – jro

+0

你必須在某種程度上嵌套,但通過重構功能可以減輕這種痛苦。另一方面,看看我幾周前發現的這篇文章:http://webapplog.com/seven-things-you-should-stop-doing-with-node-js/我沒有機會玩異步但它看起來可以幫助你解決你的結構問題。 –

相關問題