Simplify your stack and build anything. Or everything.
Build tomorrow’s web with a modern solution you truly own.
Code-based nature means you can build on top of it to power anything.
It’s time to take back your content infrastructure.

Array relations broken since 3.26 with MongoDB

default discord avatar
jannikzedlast year
5

Does anybody face similar issues like this:


Only plain objects can be passed to Client Components from Server Components. Objects with toJSON methods are not supported. Convert it manually to a simple value before passing it to props.
  {createdAt: ..., updatedAt: ..., roles: ..., email: ..., id: {buffer: ...}, loginAttempts: ..., collection: ..., _strategy: ...}


Our template worked fine until I upgraded to 3.25 (problem does still exist with 3.28). I can't really get the root-cause, but it happends in the moment that I'm adding "roles" to "users":



{
      name: 'roles',
      type: 'relationship',
      relationTo: 'roles',
      hasMany: true,
      required: false,
      saveToJWT: true,
      access: {
        create: () => true,
        update: isAdminFieldLevel,
        read: () => true,
      },
      admin: {
        position: 'sidebar',
        hidden: false,
        description: {
          en: 'User roles. Admin has full access. Editor is the most common role, with limited access. First user is always admin.',
          de: 'Benutzerrollen. Admin hat vollständigen Zugriff. Editor ist der allgemeine Benutzer, mit begrenztem Zugriff. Erster Benutzer ist immer Admin.',
        },
      },
    },


so it seems that payload is having issues with relationship fields in MongoDB. There have to be other people facing this issue as well.. I'm trying to analyse it better now and comparing the behaviour before the upgrade with the behaviour now and will update this threat.



this PR feels like the problematic one:

https://github.com/payloadcms/payload/pull/11293

seems like I can narrow it down to this hook:



 hooks: {
    beforeValidate: [
      async ({ req, data = {}, operation }) => {
        if (operation === 'create') {
          try {
            const { totalDocs } = await req.payload.find({
              collection: 'users',
              limit: 0,
            })

            // Determine which role to assign. First user should be admin
            const isAdmin =
              totalDocs === 0 ||
              (data.email &&
                process.env.ALLOWED_EMAIL_DOMAINS?.split(',').includes(data.email.split('@')[1]))

            // Find the appropriate role
            const role = await findRole(req.payload, isAdmin ? 'admin' : 'editor')

            console.log("data", data)

            if (role?.id) {
              req.payload.logger.info(`Assigning ${role.name}, id: ${role.id} role to new user`)
              return {
                ...data,
                roles: [role.id],
              }
            } else {
              req.payload.logger.error('No suitable role found for user')
            }
          } catch (error) {
            req.payload.logger.error(`Error in beforeValidate hook: ${error}`)
          }
        }
        return data
      },
    ],
  },


setting a relation doesn't seem to work any longer in this hook



Issue is, that Payload - when using the hook in this case - is writing an ObjectId in the relation field in the DB, where it does later expect a string.. that has changed.

  • discord user avatar
    alessiogr
    last year

    cc

    @423216344302092288
  • default discord avatar
    jannikzedlast year

    I can't build a reproducible example.. so still hanging here to get to the root of the issue.



    can't get this error to be logged out:



    Only plain objects can be passed to Client Components from Server Components. Uint8Array objects are not supported.
      [Uint8Array]
       ^^^^^^^^^^
    Only plain objects can be passed to Client Components from Server Components. Objects with toJSON methods are not supported. Convert it manually to a simple value before passing it to props.
      {roles: [...], email: ..., createdAt: ..., updatedAt: ..., id: {buffer: ...}, loginAttempts: ..., collection: ..., _strategy: ...}
                                                                     ^^^^^^^^^^^^^
    [Error [ValidationError]: The following field is invalid: User] {
      data: [Object],
      isOperational: true,
      isPublic: false,
      status: 400,
      [cause]: [Object]
    }


    cause and data is hidden like that

  • default discord avatar
    ritsu0455last year
    @934766301933613138

    you can check this thread I helped other person with the same question

    https://discord.com/channels/967097582721572934/1345522698826289192

    did you remove any field, changed the name or something?

  • default discord avatar
    jannikzedlast year

    I'm facing the issue on a fresh and empty DB, so that can't be the root-cause right? The thread looks similar, but just from the behaviour.. I'm currently trying to disable step by step literally everything in my payload conf, but the error is still there 😄 always testing against an empty mongoDB. All plugins all everything disabled in the Payload Config and error is still there. It's really strange



    ok, issue comes from our own entry of the mongoDB package:

    "mongodb": "6.12.0",

    that we need for our own backup & recovery plugin... that did break it for us. Any idea, how that could be improved?

  • default discord avatar
    limprushlast year

    Did you ever find a solution to that problem? It seems like other people are running into it as well - me included - and the solution from

    https://github.com/payloadcms/payload/issues/11703

    of simply updating the mongo version does not work for me. I need to have mongodb installed in my packages.json for the types and for doing

    new ObjectId()
Star on GitHub

Star

Chat on Discord

Discord

online

Can't find what you're looking for?

Get dedicated engineering support directly from the Payload team.