Alpha Camp 程式設計入門 Lesson.2-3 學習分享

    Coding

    這學期的實作大量進行「Express」、「Handlebars」、「MongoDB」、「Github版本控制」的操作來完成專案,也因此陸續碰到了一些問題,比如說與資料庫連結時的環境變數設定,或者是串接json檔案時的陣列與物件的層級,持續在學習過程中嘗試著尋求網路資源來解決問題。

    我想就來分享一下,在閱讀mongoose文件中的「Model.findByIdAndUpdate」簡化語法,我們先從Code的閱讀開始,嘗試了解Code的範例之後,在回頭閱讀英文文件,會比較容易上手。

    Test Examples:

    Model.findByIdAndUpdate(id, update, options, callback) // executes
    Model.findByIdAndUpdate(id, update, options)  // returns Query
    Model.findByIdAndUpdate(id, update, callback) // executes
    Model.findByIdAndUpdate(id, update)           // returns Query
    Model.findByIdAndUpdate()                     // returns Query
    

    我們可以從語法中觀察到可以放入的內容有[id ,update, options, callback],並且各自對應返回查詢與執行。從英文字面的翻譯可以猜測「Model.findByIdAndUpdate」到從模型中找尋這個Id和更新它,

    Solution:
    1.This function triggers the following middleware.
    這個函式會觸發中間的內容
    2.All top level update keys which are not atomic operation names are treated as set operations:。
    所有等級的更新皆適合集合。(ex.{ name: ‘jason bourne’ })

    Examples:
    修改前,我們可以看到對應的項目(中英名字、圖像網址、地址、電話…)與回傳查找的結果,有大量的程式碼相同,且大部分都指向「req.body」,由此可知這次簡化的好機會。

    router.put('/:id', (req, res) => {
      const id = req.params.id
      const name = req.body.name
      const name_en = req.body.name_en
      const category = req.body.category
      const image = req.body.image
      const location = req.body.location
      const phone = req.body.phone
      const google_map = req.body.google_map
      const rating = req.body.rating
      const description = req.body.description
    
      return Restaurant.findById(id)
        .then(restaurant => {
          restaurant.name = name
          restaurant.name_en = name_en
          restaurant.category = category
          restaurant.image = image
          restaurant.location = location
          restaurant.phone = phone
          restaurant.google_map = google_map
          restaurant.rating = rating
          restaurant.description = description
    
          return restaurant.save()
        })
        .then(() => res.redirect(`/restaurants/${id}`))
        .catch(error => consoe.log(error))
    

    修改後,透過Mongoose的語法將()的代號、參數依依進行配對。

    router.put('/:id', (req, res) => {
      const id = req.params.id
      return Restaurant.findByIdAndUpdate(id, req.body)
        .catch(error => console.log(error))
    })
    
    //運用RESTful API的語意化路由,將更新過的資料放置到對應(原來)的位置。
    //運用req.params.id將網址上的id取出來。
    //尋找符合的id並對他更新之後再回傳回來。
    //如果運作過程錯誤,則顯示error。
    

    看起來整體的程式碼從約30行縮減到5行,而該語法也可以很簡單地從字面了解功能,這次的學習非常的充實,透過實作與教材的輔助,可以讓Code寫的更精簡。