Nicholas Elliott Nicholas Elliott - 3 months ago 24
Node.js Question

mongoose findbyidandupdate just passed values

So I would like to update only the values of an object that are passed.

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);
});


My function right now will null any fields not defined in the the post request.

For example if my object has all fields defined and I try to update just the name with:

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


will result in:

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


Is there any way to perform this update with out having to pass all the other fields too?

Answer

The reason they are set to null when you don't send in all parameters is because your including null values in your updates.

The only way to prevent this is to check and ensure that your variables are set before you make the modification.

Something like:

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);
});