2016-08-21 72 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); 
}); 
相关问题