Updating an embedded document changes its _id?


Could you kindly tell me if it is normal that modifying an embedded document changes its _id; or am I doing something wrong? I am assuming it is because updating the embedded document effectively replaces the original one?

        const updatedProduct = await ProductsModel.findOneAndUpdate(
            {_id: productId},
                $set: input,
            {new: true}

Before change:


Changing the name to James Brown:

Is this intended or a sign of poor design on my part? Should this be avoided?

Thank you!


Can you console.log(input) and add the result to the question?

Hello, the input is just the following:

  recipient: { name: 'James Browley' },

I see. So you probably defined sub-schema model for the recipient so when you use $set the whole new document of Recipient model is created, and that new document get it’s own _id.

Try not to set the whole recipient sub-property, but only the fields that you really want.

const updatedProduct = await ProductsModel.findOneAndUpdate(
  { _id: productId },
  { "recipient.name": input.name },
  { new: true }
1 Like

Hey again,

Thanks for the explanation.

Would you happen to know how to properly describe what you wrote:

{ "recipient.name": input.name } 

In a standalone Typescript object and interface?


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