diff --git a/packages/core/database/src/__tests__/fields/sequence-field.test.ts b/packages/core/database/src/__tests__/fields/sequence-field.test.ts index 5005b7aa4..a575e7c89 100644 --- a/packages/core/database/src/__tests__/fields/sequence-field.test.ts +++ b/packages/core/database/src/__tests__/fields/sequence-field.test.ts @@ -216,6 +216,31 @@ describe('string field', () => { const item4 = await TestModel.create(); expect(item4.get('name')).toBe('1'); }); + + it('last record has no value of this field', async () => { + const testCollection = db.collection({ + name: 'tests', + fields: [], + }); + await db.sync(); + + const TestModel = db.getModel('tests'); + const item1 = await TestModel.create(); + expect(item1.get('name')).toBeUndefined(); + + testCollection.addField('name', { + type: 'sequence', + patterns: [ + { + type: 'integer' + } + ] + }); + await db.sync(); + + const item2 = await TestModel.create(); + expect(item2.get('name')).toBe('0'); + }); }); describe('date pattern', () => { diff --git a/packages/core/database/src/fields/sequence-field.ts b/packages/core/database/src/fields/sequence-field.ts index 28acf97f0..b6273b273 100644 --- a/packages/core/database/src/fields/sequence-field.ts +++ b/packages/core/database/src/fields/sequence-field.ts @@ -44,7 +44,7 @@ sequencePatterns.register('integer', { const { lastRecord = null } = this.options; if (typeof options.current === 'undefined') { - if (lastRecord) { + if (lastRecord && lastRecord.get(this.options.name)) { // if match current pattern const matcher = this.match(lastRecord.get(this.options.name)); if (matcher) { @@ -115,6 +115,8 @@ export interface SequenceFieldOptions extends BaseColumnFieldOptions { } export class SequenceField extends Field { + matcher: RegExp; + get dataType() { return DataTypes.STRING; } @@ -170,7 +172,7 @@ export class SequenceField extends Field { }; match(value) { - return value.match(this.matcher); + return typeof value === 'string' ? value.match(this.matcher) : null; } parse(value: string, patternIndex: number): string {