Nicholas Elliott Nicholas Elliott - 6 months ago 42
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(, {
$set: {
narrative: req.body.narrative,
startdate: req.body.startdate,
enddate: req.body.enddate,
}, {new: true},
function(err, Event) {
if (err) throw err;


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?


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. = ? 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; = ? undefined; 

  {$set: modifications},
  {new: true},
  function(err, Event) {
    if (err) throw err;