DVassilev
DVassilev

Reputation: 242

Updating only inputted fields

I'm making a RESTful API but I have run into some trouble. I want to update a row with only the values that have been passed through. So with the same endpoint the user can edit just the 'name', both the 'name' and 'type' or only the 'type'.

Here is a snipped of what I currently have:

Group.update({
  created_by: req.user._id,
  _id: req.params.group_id
}, {
  name: req.body.name,
  $addToSet: { users: req.body.users }
},

I'd like to make it so that if no users are passed through or no name is passed through it would still the update the other value. Could anyone point me in the right direction please?

Thanks, Daniel

Upvotes: 0

Views: 352

Answers (1)

Jake Sellers
Jake Sellers

Reputation: 2439

You need to build the query dynamically.

var find = {
      created_by: req.user._id,
      _id: req.params.group_id
}

var update = {};
if(req.body.name) {
    update.name = req.body.name;
}
if(req.body.users) {
    update['$addToSet'] = {};
    update['$addToSet'].users = req.body.users;
}

Group.update(find, update, callback);

Its not the prettiest way but it should give you an idea of how to tackle this.

Upvotes: 1

Related Questions