Skip to content

Payload migration script to v2 not working out of the box with Azure Cosmos DB #4161

Closed as not planned

Description

@jkauppinen

Link to reproduction

No response

Describe the Bug

Migration script specified in v2 instructions doesn't work out of the box with Azure Cosmos DB for MongoDB. Using local mongo instance the same script worked, so this is azure specific problem.

Payload version: 2.1.1
Azure Cosmos DB for MongoDB version: 4.2

Error

npm run payload migrate --verbose
[14:56:31] INFO (payload): Connected to MongoDB server successfully!
[14:56:31] INFO (payload): Starting Payload...
/src/cms/node_modules/mongodb/lib/cmap/connection.js:231
                    callback(new error_1.MongoServerError(document));
MongoServerError: Error=2, Details='Response status code does not indicate success: BadRequest (400); Substatus: 0; ActivityId: XXXXXX; Reason: (Response status code does not indicate success: BadRequest (400); Substatus: 0; ActivityId: XXXXXXXX; Reason: (Response status code does not indicate success: BadRequest (400); Substatus: 0; ActivityId: XXXXXX; Reason: (Message: {"Errors":["The index path corresponding to the specified order-by item is excluded."]}
ActivityId: XXXXXXX, Request URI: /apps/XXXXXXX/services/XXXXX/partitions/XXXXX/replicas/YYYYYY/, RequestStats: Microsoft.Azure.Cosmos.Tracing.TraceData.ClientSideRequestStatisticsTraceDatum, SDK: Windows/10.0.17763 cosmos-netstandard-sdk/3.18.0);););
    at Connection.onMessage (/src/cms/node_modules/mongodb/lib/cmap/connection.js:231:30)
    at MessageStream.<anonymous> (/cms/node_modules/mongodb/lib/cmap/connection.js:61:60)
    at MessageStream.emit (node:events:514:28)
    at processIncomingData (/cms/node_modules/mongodb/lib/cmap/message_stream.js:125:16)
    at MessageStream._write (/cms/node_modules/mongodb/lib/cmap/message_stream.js:33:9)
    at writeOrBuffer (node:internal/streams/writable:447:12)
    at _write (node:internal/streams/writable:389:10)
    at Writable.write (node:internal/streams/writable:393:10)
    at TLSSocket.ondata (node:internal/streams/readable:817:22)
    at TLSSocket.emit (node:events:514:28) {
  ok: 0,
  code: 2,
  codeName: 'BadValue',
  [Symbol(errorLabels)]: Set(0) {}

Payload configuration

indexSortableFields enabled in payload.config.ts and using mongooseAdapter with standard uri configuration.

Short term fix

I was able to fix this by manually creating the indexes for each collection, for example:

db.myCollection.createIndex({ "updatedAt": -1 });

Suggestions

  1. Migration could be added with a parameter for index handling. The indexes could be created in the migration script itself.
    OR
  2. Update the migration to not rely on updatedAt

To Reproduce

Follow migration steps for existing v1 payload database that uses Azure Cosmos DB for MongoDB

https://github.com/payloadcms/payload/releases/tag/v2.0.0

Payload Version

2.1.1

Adapters and Plugins

db-mongodb, bundler-webpack, richtext-slate

Activity

  1. added
    status: needs-triage
    on Nov 15, 2023
  2. self-assigned this
    on Nov 15, 2023
  3. added
    status: cant-reproduce
    on Nov 15, 2023
  4. DanRibbens commented on Nov 15, 2023

    @DanRibbens
    Contributor

    It seems to me like you shouldn't have had to create that index yousrself if your project was already using indexSortableFields. If that was working correctly, you shouldn't have had to do this. Did you have to do it for every collection that has versions enabled?

    I did spin Payload with cosmos DB to test that sorting on updatedAt desc works with listSortableFields enabled and it did create indexes. This was on latest Payload. I didn't try going back to 1.x but the way we do indexes hasn't changed in a long time.

    Since I can't reproduce the issue I'm going to close it as there isn't much we can do. There might be something else at play, like timestamps: false or some other part of your config causing this.

  5. DanRibbens commented on Nov 15, 2023

    @DanRibbens
    Contributor

    If more people report this issue we can revisit it by adding createIndex to the migration script.

  6. jkauppinen commented on Nov 16, 2023

    @jkauppinen
    Author

    @DanRibbens My suspicion is that in order to reproduce this problem, you need to create the database with older version of payload, especially since the migration script is expected to be used on v1 database. If you haven't changed index handling between 1.8.3 and 2.x, then there might be a problem with global collection indexing and/or migration script when using Cosmos DB. The current migration script uses "updatedAt" for sorting global collections. The "timestamps: false" on "normal" collection seems to explain collections outside global.

    • Target DB payload data structure version: 1.8.3
    • Global collection did not have index
    • Normal Collections that had timestamps: false were missing the index

    Bicep repro:

    resource dbAccount 'Microsoft.DocumentDB/databaseAccounts@2023-04-15' = {
      name: 'loveThemIndexes'
      location: location
      kind: 'MongoDB'
      properties: {
        databaseAccountOfferType: 'Standard'
        locations: [
          {
            locationName: location
            failoverPriority: 0
          }
        ]
        capabilities: [
          {
            name: 'EnableServerless'
          }
          {
            name: 'EnableMongo'
          }
        ]
        apiProperties: {
          serverVersion: '4.2' 
        }
      }
    }
    
    resource mongoDb 'Microsoft.DocumentDB/databaseAccounts/mongodbDatabases@2023-04-15' = {
      parent: dbAccount
      name: dbName
      properties: {
        resource: {
          id: dbName
        }
        options: {}
      }
    }

    Config example:

    export default buildConfig({
      serverURL: process.env.PAYLOAD_PUBLIC_SERVER_URL,
      rateLimit: {
        trustProxy: true,
      },
      // For Azure Cosmos DB
      indexSortableFields: true,
      routes: {
        api: "/cms-api",
        admin: "/cms-admin",
      },
      cors: "*",
      admin: {
        user: Users.slug,
    
      },
      collections: [c1,c2,c3],
      globals: [g1,g2,g3],
    });

    Global collection indexes created by payload:
    global-indexes

    Excerpt from generated migration script:

      // For each global
      await Promise.all(
        payload.config.globals.map(async ({ slug, versions }) => {
          if (versions) {
            const VersionsModel = payload.db.versions[slug]
    
            await VersionsModel.findOneAndUpdate(
              {},
              { latest: true },
              {
                sort: { updatedAt: -1 },
              },
            ).exec()
    
            payload.logger.info(`Migrated the "${slug}" global.`)
          }
        }),
      )
  7. github-actions commented on Sep 7, 2024

    @github-actions
    Contributor

    This issue has been automatically locked.
    Please open a new issue if this issue persists with any additional detail.

  8. locked as resolved and limited conversation to collaborators on Sep 7, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

status: cant-reproducestatus: needs-triage

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions