2016-08-21 41 views
0

所以我想只更新傳遞的對象的值。mongoose findbyidandupdate剛通過值

  Event.findByIdAndUpdate(req.body.id, { 
      $set: { 
       name: req.body.name, 
       narrative: req.body.narrative, 
       startdate: req.body.startdate, 
       enddate: req.body.enddate, 
       site: req.body.site 
      } 
      }, {new: true}, 
      function(err, Event) { 
       if (err) throw err; 

       res.send(Event); 
      }); 

我現在的函數將null在post請求中沒有定義的任何字段。
例如,如果我的對象的所有字段定義,我嘗試更新只是名字:

{ 
    "id": "57b8fa4752835d8c373ca42d", 
    "name": "test" 
} 

將導致:

{ 
"_id": "57b8fa4752835d8c373ca42d", 
"name": "test", 
"narrative": null, 
"startdate": null, 
"enddate": null, 
"site": null, 
"__v": 0, 
"lastupdated": "2016-08-21T00:48:07.428Z", 
"sponsors": [], 
"attendees": [] 
} 

有什麼辦法來執行具有了此更新通過所有其他領域呢?

+1

你確定,你有你'req.body'所有的價值呢? –

回答

2

當您不發送所有參數時,將它們設置爲null的原因是因爲您的更新中包含null值。

防止這種情況的唯一方法是檢查並確保在進行修改之前設置變量。

喜歡的東西:

var modifications = {}; 

// Check which parameters are set and add to object. 
// Indexes set to 'undefined' won't be included. 
modifications.name = req.body.name ? 
    req.body.name: undefined; 

modifications.narrative = req.body.narrative ? 
    req.body.narrative: undefined; 

modifications.startdate = req.body.startdate ? 
    req.body.startdate: undefined; 

modifications.enddate = req.body.enddate ? 
    req.body.enddate: undefined; 

modifications.site = req.body.site ? 
    req.body.site: undefined; 


Event.findByIdAndUpdate(
    req.body.id, 
    {$set: modifications}, 
    {new: true}, 
    function(err, Event) { 
    if (err) throw err; 

    res.send(Event); 
}); 
相關問題