Node.js mongoose findbyidandupdate刚刚传递的值

Node.js mongoose findbyidandupdate刚刚传递的值,node.js,mongodb,Node.js,Mongodb,因此,我只想更新传递的对象的值 Event.findByIdAndUpdate(req.body.id, { $set: { name: req.body.name, narrative: req.body.narrative, startdate: req.body.startdate, enddate: req.bod

因此,我只想更新传递的对象的值

            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);
            });
我的函数现在将使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": []
}

是否有任何方法可以执行此更新而不必同时传递所有其他字段?

当您不发送所有参数时,它们被设置为
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);
});

您确定
req.body
中有所有值吗?