Migrating data to _id fields

default discord avatar
kariyngva
2 months ago
7

Hey, so I have a collection (Tag) which started out with just a

name

text field. To ease querying documents by tags I changed the field to

id

but I'm having issues migrating the value in

name

to the

id

field.



My migration fails,


await db.collection('tags').updateMany({}, [{ $set: { _id: '$name.is' } }]);

ERROR: Could not migrate up 20230327105207-tag-custom-id-field.js: After applying the update, the (immutable) field '_id' was found to have been altered to _id: "test" MongoServerError: After applying the update, the (immutable) field '_id' was found to have been altered to _id: "test"

I know this is a MongoDB issue rather than Payload, but I'm hoping someone could point me in the right direction 🤞

  • default discord avatar
    thisisnotchris
    2 months ago

    @kariyngva I'm pretty sure

    _id

    is reserved and shouldn't be edited



    In any case, I would suggest reverting those changes and picking a different property name

  • default discord avatar
    kariyngva
    2 months ago

    Well this is what you get when using Custom IDs:

    https://payloadcms.com/docs/fields/overview#customizable-id

    When you set a field name to

    id

    it becomes

    _id

    . The issue here is migrating the

    name

    value i.e.

    test

    to be the id 🙂

  • discord user avatar
    Jarrod
    Payload Team
    last month

    If you are doing this just to ease querying, I would prob advise to keep the "advanced" query and set

    index: true

    on your name field.

  • default discord avatar
    kariyngva
    last month

    Thanks Jarrod, that makes sense 🙏

  • default discord avatar
    Teun
    last month

    If you do want to use the custom id field, then you'll have to write a custom migration for it. Mongo will not let you update an id. Only way to accomplish that is the create a new document with the required id and remove to old one.

  • default discord avatar
    kariyngva
    last month

    Yeah that's what I figured. Just wanted to check if anyone had a better solution. Thanks Tuen!

Open the post
Continue the discussion in Discord
Like what we're doing?
Star us on GitHub!

Star

Connect with the Payload Community on Discord

Discord

online

Can't find what you're looking for?

Get help straight from the Payload team with an Enterprise License.