问题描述
我刚刚将我的rxdb模式版本从0更改为1,以便添加deletedAt
属性。我添加了从版本0到版本1的迁移策略。
现在我遇到此错误:“文档迁移失败的最终文档与最终架构不匹配”。最终文档在以下屏幕快照中:
我认为也许我必须添加_rev
字段;在架构中添加_rev
并不能消除错误,因此我将其撤回了。与deleted
字段同上(抱怨我不能将其添加为顶级属性)。因此,我不知为何最终对象与预期架构不同?
类型信息
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',required: ['id','text','isCompleted','createdAt','updatedAt','deletedAt'],indexes: ['createdAt']
}
迁移者代码
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;
}
}
})
解决方法
问题是我刚刚添加的deletedAt
在json模式中的定义如下:
deletedAt: {
type: 'string',format: 'date-time'
},
...,而我在创建版本时将默认值设置为''
(空字符串)
0个对象。并且空字符串对于json模式中的日期时间格式无效。因此,当将对象迁移到版本1时,转换最终以一个对象deletedAt
进行,该对象没有通过验证。
解决方案:
-
通过从
- 更新rxdb集合的 json模式。
- 更改javascript对象的任何本地打字稿类型,以使
deletedAt
是可选属性或默认为null的属性。 This is okay because null is valid date-time format string in json schema。
updatedAt
数组中删除 required: [...]
,不知道为什么仅在需要迁移版本0的对象时才进行某种形式的验证。