Search code examples
pouchdbrxdb

rxdb: migration of document failed final document does not match final schema


I just changed my rxdb schema version from 0 to 1 in order to add a deletedAt attribute. I added a migration strategy for going from ver 0 to 1.

Now I'm getting this error: "migration of document failed final document does not match final schema". The final doc is in screenshot below:

console error from react app using rxdb

I thought maybe I had to add the _rev field; adding _rev to schema didn't remove the error, so I've taken it back out. Ditto with a deleted field (complains I can't add it as a top-level attribute). So I am at a loss as to why else the final object differs from the expected schema?

type info

export type TodoType = {
  id: string
  text: string
  isCompleted: boolean
  createdAt: string
  updatedAt: string
  deletedAt: string
}
//...
export const todoSchema: RxJsonSchema<TodoType> = {
  title: 'todo schema',
  description: 'todo schema',
  version: 1, // just changed this from 0 to 1
  type: 'object',
  properties: {
    id: {
      type: 'string',
      primary: true
    },
    text: {
      type: 'string'
    },
    isCompleted: {
      type: 'boolean'
    },
    createdAt: {
      type: 'string',
      format: 'date-time',
      // index: true,   
    },
    updatedAt: {
      type: 'string',
      format: 'date-time'
    },
    deletedAt: {
      type: 'string',
      format: 'date-time'
    },
  },
  required: ['id', 'text', 'isCompleted', 'createdAt', 'updatedAt', 'deletedAt'],
  indexes: ['createdAt']
}

migrator code

  await myDatabase.collection({
    name: 'todos',
    schema: todoSchema,
    methods: todoMethods,
    statics: todoCollectionMethods,
    migrationStrategies: {
      // 1 means, this transforms data from version 0 to version 1
      1: function(oldDoc: TodoDocument) {
        oldDoc.updatedAt = oldDoc.updatedAt === '' ? oldDoc.createdAt : oldDoc.updatedAt
        oldDoc.deletedAt = oldDoc.deleted ? oldDoc.updatedAt : ''
        return oldDoc;
      }
    }
  })

Solution

  • The problem was that deletedAt, which I had just added, was defined like this in the json schema:

        deletedAt: {
          type: 'string',
          format: 'date-time'
        },
    

    ... and I was defaulting the value to '' (empty string) when I was creating version 0 objects. And an empty string is invalid for date-time format in json schema. So when the objects were being migrated to version 1, the transform ended up with an object that had deletedAt, which doesn't pass validation.

    Solution:

    Not sure why some kind of validation didn't kick in while saving the version 0 objects, only when it came time to migrate them.