0

This question is in regards to the mongodb go driver which I am fairly new to. The following is the update parameter I am using for my request.

update := bson.D{{"$set", bson.D{
        {"firstName", person.FirstName},
        {"lastName", person.LastName},
    }}}

persons.FindOneAndUpdate(ctx, filter, update, opts).Decode(&updatedPerson)

The issue with this is that sending a request that omits a certain field would result in the field being removed. For example, sending a request like {"firstName": "Bob"} would remove the existing "lastName" field if there was one.

Conversely, if I omit the $set operator on the field entirely, the field remains unaffected even if it is not passed in during the request. As an example, the below update parameter will not remove the "lastName" field if it is not passed.

update := bson.D{{"$set", bson.D{{"firstName", person.FirstName}}}}

Are there any options I can specify to change this behaviour? The desired effect is a function that ignores any unspecified fields in the requests and only updates the fields that were provided in the request body, something akin to how it works with the mongoose library (https://mongoosejs.com/docs/api.html#model_Model.findOneAndUpdate).

Capybara
  • 1
  • 1
  • @Flimzy, I am not entirely sure what you mean by that, I don't seem to have any problems performing partial updates, it's just that when I specify $set on a specific field it seems to expect a value otherwise it removes the field – Capybara Jul 16 '20 at 07:54
  • I guess I misunderstood your question. Sorry. – Jonathan Hall Jul 16 '20 at 07:56
  • You will need to build that update object dynamically, like https://stackoverflow.com/a/55307419/2282634 – Joe Jul 16 '20 at 11:04

0 Answers0