Search code examples
javascriptmongodbmongoose

Mongoose partial update of an object


I have a simple user model:

{
  _id: "59d72070d9d03b28934b972b"
  firstName: "first"
  lastName: "last"
  email: "[email protected]"
  subscriptions: {
    newsletter: true,
    blog: true
  }
}

I'm trying to do partial updates on the subscriptions object. I'm passing the id of the user and a payload object that can have either one or both properties of the object. Let's say I only want to update newsletter and set it to false. I'll send:

{ id: "59d72070d9d03b28934b972b", payload: { newsletter: false } }

And then:

const user = await User.findByIdAndUpdate(
  args.id,
  { $set: { subscriptions: args.payload } },
  { upsert: true, new: true }
);

This will return:

subscriptions: {
  newsletter: false
}

Is there a way to only modify the newsletter property when I only pass newsletter in the payload object without deleting the other properties? I know I only have two properties in this example, but in time, the object will keep expanding.


Solution

  • I ended up doing the following:

    const user = await User.findById(args.id);
    
    // merge subscriptions
    user.subscriptions = Object.assign({}, user.subscriptions, args.payload);
    
    return user.save();