Updating an embedded document changes its _id?

Hello,

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}
        ).exec()

Before change:

image

Changing the name to James Brown:
image

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

Thank you!

Hi,

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 }
).exec()
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?

Thanks!

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