2017-03-22 45 views
0

最近我開始使用MEAN堆棧構建自己的RESTful API。到現在爲止還挺好。昨天我碰到了一個小問題,這是我一直在努力解決,但沒有成功的結果已經看到到現在爲止...Mongoose模式,具有默認值的嵌套對象

我有一個貓鼬架構,看起來像這樣:

const hotelSchema = new mongoose.Schema({ 
    name: { 
     type: String, 
     required: true 
    }, 
    stars: { 
     type: Number, 
     min: 0, 
     max: 5, 
     "default": 0 
    }, 
    services: [String], 
    description: { 
     type: String, 
     "default": "No description" 
    }, 
    photos: [String], 
    currency: { 
     type: String, 
     "default": "Not specified" 
    }, 
    reviews: [reviewSchema], 
    rooms: [roomSchema], 
    location: { 
     address: { 
      type: String, 
      "default": "Not specified" 
     }, 
     // Always store coordinates longitude E/W, latitude N/S order 
     coordinates: { 
      type: [Number], 
      index: '2dsphere' 
     } 
    } 
}); 

而且這是我如何創建模型實例:

Hotel 
     .create({ 
      name: req.body.name, 
      description: req.body.description, 
      stars: parseInt(req.body.stars, 10), 
      services: _splitArray(req.body.services), 
      photos: _splitArray(req.body.photos), 
      currency: req.body.currency, 
      location: { 
       address: req.body.address, 
       coordinates:[ 
        parseFloat(req.body.lng), 
        parseFloat(req.body.lat) 
       ] 
      } 

一切都很完美,並且如預期的那樣有一個小細節。我正在使用Advanced Rest Client進行POST請求。它可以看到下面:

Request with Rest Client

而這就是我得到的迴應: Response from Rest Client

所以問題是,如果我不輸入地址,我想看看默認值,因爲它可以在架構中看到 - 「未指定」。不幸的是,我無法做到這一點。

你能幫我嗎?

+0

請從關鍵「default」中刪除雙引號,然後再次檢查。 –

+0

保持它只是默認,而不是「默認」 –

+0

試過了,不起作用。不管怎麼說,還是要謝謝你 –

回答

0

解決!

事實上,它似乎確實工作正常。當我通過id獲取新創建的酒店的GET請求時,它實際上會按照我的意願將其返回,並將「地址」設置爲「未指定」。

使用Model.create()函數創建酒店後,返回的回調包含酒店,但沒有「地址」爲「未指定」的事實。

我也試過郵遞員的請求,結果是一樣的 - 沒有地址設置。

但無論如何,我看到它實際上工作。我將嘗試找出回調中返回的對象爲什麼沒有完成的原因......