0

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?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
gaurav joshi
  • 77
  • 1
  • 8

1 Answers1

1

Work with the $ positional operator.

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

Demo @ Mongo Playground

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Yong Shun
  • 35,286
  • 4
  • 24
  • 46