ChangeJob
ChangeJob

Reputation: 41

findOneAndUpdate in mongoose

I have a json documnent lit this:

{ "mainData": { "id": "2131231312.." "data": { "oneNode": { ... } "otherNode": { ... } "anyNode": { .... } } } In PATCH someone send me: { "mainData": { "id" "2131231312.." "oneNode": { "field1": "value" } } }

Trying to use findOneAndUpdate() to change an object inside subnode. I'd like to change a value in "oneNode" or create node "oneNode" in "data" is not presente. Any suggestions?

Thanks.

I use

DBValue.findOneAndUpdate({ "mainData.id": instanceId }, { "mainData": { "id" "2131231312..", "oneNode": { "field1": "value"}})

Upvotes: 0

Views: 49

Answers (1)

wikimind
wikimind

Reputation: 929

If I understand your question correctly, you can use the $set operator to only set specific points of data to the document. It can be used to update existing values OR to add new values.

https://www.mongodb.com/docs/manual/reference/operator/update/set/

Perhaps something like this:

DBValue.findOneAndUpdate(
  { "mainData.id": instanceId },
  {
    $set: {
      'mainData.someExistingNode.someField': 1234,
      'mainData.someNewField': 22
    }
  }
)

Upvotes: 1

Related Questions