Updating a nested object in a document using mongoose

I’ve been trying to update a particular object in a Mongodb document without any luck using the findOneAndUpdate() method. This is what my collectiom looks like

{
  _id: new ObjectId("61da0ab855483312e8f4483b"),
  products: [
    {
      createdAt: 2022-01-08T22:05:44.635Z,
      _id: new ObjectId("61da0ab855483312e8f4483c"),
      productCode: 'otf',
      productName: 'facebookmeta',
      claims: [Array],
      permissions: []
    },
    {
      createdAt: 2022-01-08T22:05:44.635Z,
      _id: new ObjectId("61da0ab855483312e8f4483f"),
      productCode: '4pf',
      productName: 'twitteroauth',
      claims: [Array],
      permissions: [Array]
    }
  ],
  __v: 0
}

When i try something like this. i am trying to find a singular object based on its product code and update that object

ProductModel.findOneAndUpdate({productCode: userData.productCode}, dataToBeUpdated, {new: true})

it returns a

Performing an update on the path '_id' would modify the immutable field '_id

i am suspecting that MongoDB is applying query conditions on collection and returns the result with the matching documents so its probably returning both objects which is probably the cause of the error i am encountering but i could be wrong.

How can i efficiently point it to the right object and perform an update

Hi @muhammed_ogunsanya,
Try this:

let userData = {productCode: "4pf"}
let dataToBeUpdated = {claims: ["abc", "def"]}
ProductModel.findOneAndUpdate({"products.productCode": userData.productCode}, {$set: {"products.$": dataToBeUpdated}})

See $ (update) for more information.
Goodluck,
Rafael,

3 Likes

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.