1

I have the following BSON data in MongoDB:

[
  {
     partyName : "p1",
     poNumber : "789",
  },
  {
     partyName : "p2",
     poNumber : "700",
  },
  {
     partyName : "p3",
     poNumber : "889",
  }
]

I want to replace the object where partyName is "p2" with a new object. I tried this

const user1 = await User.findOneAndUpdate({"array.partyName" :"p2"},{$set:{array:newObject}})

It replaces the object "p2" but it deletes the other objects (p1 and p3). I want to keep p1, and p3, but only update the p2 objects.

How can I overcome this problem?

1 Answer 1

1

Work with the $ positional operator.

await User.findOneAndUpdate(
  { "array.partyName" :"p2" },
  { $set: { "array.$": newObject } }
)

Demo @ Mongo Playground

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.